简体   繁体   中英

Set default action for home button in action bar for all activities

I want to declare an activity my app's 'home' activity. Now, I can setup the action of home button in each activity using

public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home) {
        Intent i = new Intent(getApplicationContext(),
                HomeScreen.class);
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
    }
    return true;
}

I've declared my HOME activity in manifest using

<activity
        android:name=".HomeScreen"
        android:label="@string/app_name"
        android:theme="@style/Theme.Sherlock" >

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.HOME" />
            <category android:name="android.intent.category.LAUNCHER" />
</activity>

I've also enabled the showHome option of actionBar using

<style name="ActionBarCustom" parent="@style/Widget.Sherlock.ActionBar">
    <item name="android:displayOptions">showHome|showTitle</item>
    <item name="displayOptions">showHome|showTitle</item>
    <item name="android:logo">@drawable/arrow_icon</item>
</style>

Now, when I click my home button from an activity where I've not specified

getSupportActionBar().setHomeButtonEnabled(true);

specifically, it doesn't show the indication that the button has been clicked. I want a default action for my home button. I know I'm missing a very small thing if I'm right. I've gone through a lot of stuff on stack overflow & developer.android but all in vain. Can anyone please help? I want to set a default action for home button.

In addition I may also want to setup a custom action bar using showCustom but again I want to define a default action for the other button (I want to setup in action bar) at one place rather than specifying it in every activity).

(I'm testing on android 2.2.)

你错过了

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Create a Activity call it BaseActivity.

Now derive all activities where you want the functionality and override the onOptionsItemSelected there

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM