Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle "Up" button?

Tags:

android

How to handle "Up" button (SDK version 11+)? I am referring to the one at the top of screen, that holds the application icon.

In Android Design articles it was named as "Up button", but I didn't found it (or similar) in KeyEvent fields.

like image 422
Dmitry Zaytsev Avatar asked Jan 16 '12 22:01

Dmitry Zaytsev


People also ask

Which are the ways to handle onClick event of button?

When the user clicks a button, the Button object receives an on-click event. To make click event work add android:onClick attribute to the Button element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event.

How to add button to action bar?

Add Action Buttons To add actions to the action bar, create a new XML file in your project's res/menu/ directory. The app:showAsAction attribute specifies whether the action should be shown as a button on the app bar.


2 Answers

Implement onOptionsItemSelected() and watch for android.R.id.home "menu" events, as is described in the documentation.

@Override public boolean onOptionsItemSelected(MenuItem item) {     switch (item.getItemId()) {         case android.R.id.home:             // do something useful             return(true);     }      return(super.onOptionsItemSelected(item)); } 
like image 108
CommonsWare Avatar answered Sep 27 '22 15:09

CommonsWare


First change your AndroidManifest.xml file to have a parent activity declared. Eg

    <activity android:name=".theory"               android:parentActivityName=".MainActivity"         android:label="@string/theory"         />     <activity android:name=".experimental"               android:parentActivityName=".MainActivity"         android:label="@string/exp"         /> 

Do this for all the activities other than the MainActivity. Note the parentActivityName xml code

Then go to the respective java files and add the following code

    ActionBar ab = getSupportActionBar();     ab.setDisplayHomeAsUpEnabled(true); 

You have you up button enabled now.

like image 38
Sri Ram Avatar answered Sep 27 '22 15:09

Sri Ram