javaandroidandroid-3.0-honeycomb

How to implement the Android ActionBar back button?


I have an activity with a listview. When the user click the item, the item "viewer" opens:

List1.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {

        Intent nextScreen = new Intent(context,ServicesViewActivity.class);
        String[] Service = (String[])List1.getItemAtPosition(arg2);

        //Sending data to another Activity
        nextScreen.putExtra("data", datainfo);
        startActivityForResult(nextScreen,0);
        overridePendingTransition(R.anim.right_enter, R.anim.left_exit);
    }
});

This works fine, but on the actionbar the back arrow next to the app icon doesn't get activated. Am I missing something?


Solution

  • Selvin already posted the right answer. Here, the solution in pretty code:

    public class ServicesViewActivity extends Activity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // etc...
            getActionBar().setDisplayHomeAsUpEnabled(true);
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
            case android.R.id.home:
                NavUtils.navigateUpFromSameTask(this);
                return true;
            default:
                return super.onOptionsItemSelected(item);
            }
        }
    }
    

    The function NavUtils.navigateUpFromSameTask(this) requires you to define the parent activity in the AndroidManifest.xml file

    <activity android:name="com.example.ServicesViewActivity" >
        <meta-data
         android:name="android.support.PARENT_ACTIVITY"
         android:value="com.example.ParentActivity" />
    </activity>
    

    See here for further reading.