I'm trying to make my top action bar icon to allow users to go back to previous screen. I tried to implement these codes. But none are working. Can anyone please guide me on this. I know this looks simple, I'm new to android . Below are my codes.
Problem : When i tap on the icon button it just cleared my screen without going to the previous screen.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_item);
checkInternetConnection();
getSupportActionBar().setDisplayHomeAsUpEnabled(true); //<--THIS
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
Intent intent = new Intent(this, SingleViewActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_TASK_ON_HOME);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
This is the way I do it:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; go home
Intent intent = new Intent(this, main.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
}
return true;
}
In your ressources(res) go to menu and add this make sur u have some button back for in your drawable
<?xml version="1.0" encoding="utf-8"?>
<item
android:id="@+id/back"
android:icon="@drawable/back1"
android:showAsAction="always|withText"
android:title="back"/>
now in your activity
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
break;
case R.id.back:
Intent in = new Intent(this, <classname which you want to go back>.class);
startActivity(in);
break;
}
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With