androidandroid-activityup-button

Want to run the up-button only after api level 11


I wants the up-button only on API level 11 and later, but my program need to run on all devices. How can i do this?

ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);

OR

Can I add up-button to all API levels? Please advise...


Solution

  • You can check for the Android OS version install on the device with this:

    int currentAPIVersion = android.os.Build.VERSION.SDK_INT;
    
    if (currentAPIVersion >= android.os.Build.VERSION_CODES.HONEYCOMB) {
    
        // RUN THE CODE SPECIFIC TO THE API LEVELS ABOVE HONEYCOMB (API 11+)   
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
    }
    

    You would have to run this check in every Activity part of your app and perhaps, also provide an alternative when the API level is below 11.

    There will however be a disparity in the UX for users on different API levels on their devices. To bridge this, you could consider looking at the ActionBarSherlcock Library that will help you bring parity to your app regardless of the API level (2.x and above).

    UPDATED:

    To add an action to the Home Button that will go back to the previous Activity, override the onOptionsItemSelected() method as shown below. Note the use of android.R.id.home in the code. You can add additional cases to the switch block if you have additional menu items that will be shown in the ActionBar in the same onOptionsItemSelected().

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    
        switch (item.getItemId()) {
    
        case android.R.id.home: {
            this.finish();
    
            return true;
        }
    
        default:
            return super.onOptionsItemSelected(item);
        }
    }