Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ActionBarSherlock On Top Icon Back

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);    
   }
}
like image 633
Android Novice Avatar asked Nov 30 '22 23:11

Android Novice


2 Answers

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;
}
like image 90
JackTools.Net Avatar answered Dec 09 '22 18:12

JackTools.Net


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;
}
like image 25
Sourabh Saldi Avatar answered Dec 09 '22 19:12

Sourabh Saldi