I'm kind of new to Android. I'm implementing a small android application. It has 3 pages.
Page A
Page B
Page C
There are buttons in Page A and Page B which can go to Page C. What I need to know is, when I goto Page C by clicking on Page A button I need to go back to Page A using onBackPressed()
and when I goto Page C by clicking on Page B button I need to go back to Page B using onBackPressed()
Here is the code I used.
@Override
public void onBackPressed()
{
super.onBackPressed();
startActivity(new Intent(C.this, A.class));
finish();
}
As far as I know I can't call two onBackPressed()
in the same class.
So, what should I do?
Start Activity C from A/B
btnFromC.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), C.class);
finish();
startActivity(intent);
}
});
Try this, is not the Best answer but it works:
Activity A:
btnFromC.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), C.class);
intent.putExtra("comeFrom", 0);
startActivity(intent);
}
});
Activity B:
btnFromC.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), C.class);
intent.putExtra("comeFrom", 1);
startActivity(intent);
}
});
Activity C:
int comeFrom;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = this.getIntent();
comeFrom = intent.getIntExtra("comeFrom", 0);
}
@Override
public void onBackPressed()
{
super.onBackPressed();
Intent intent = null;
switch(comeFrom){
case 0:
intent = new Intent(getApplicationContext(), A.class);
break;
case 1:
intent = new Intent(getApplicationContext(), B.class);
break;
}
startActivity(intent);
}
Solve your problem?