How to enable the home button to return to a common activity?

陌路散爱 提交于 2019-12-12 01:22:50

问题


I use ActionbarSherlock and would like to enable the home button ...
Therefore I call setHomeButtonEnabled(true) in my base activity.

public class BaseFragmentActivity extends SherlockFragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.Theme_Sherlock);
        super.onCreate(savedInstanceState);
        getSupportActionBar().setHomeButtonEnabled(true); // Here
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home: {
                Intent intent = new Intent(this, HomeActivity.class);
                // startActivity(intent);
                // startActivityIfNeeded(intent, 0);
                return true;
            }
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

When I use startActivity(intent) or startActivityIfNeeded(intent, 0) the HomeActivity is recreated everytime (the activity renders a map and recreating it is annoying).

  • I do not want to call finish() since it just takes me back one step in the app hierarchy. Instead I always want to return to the HomeActivity.
  • Further it would be nice if the behavior could be configured in AndroidManifest.xml as it is described for the ActionBar and setDisplayHomeAsUpEnabled().
  • It might also be common sense to clear the backstack when I return to the HomeActivity. What is your opinion on that?

回答1:


I'd consider using the single instance launchmode for that activity.

AndroidManifest.xml

<activity  android:launchMode="singleInstance">
...
</activity>

Reference

Only allow one instance of this activity to ever be running. This activity gets a unique task with only itself running in it; if it is ever launched again with the same Intent, then that task will be brought forward and its Activity.onNewIntent() method called. If this activity tries to start a new activity, that new activity will be launched in a separate task. See the Tasks and Back Stack document for more details about tasks.




回答2:


In the Android documentation I found what I was searching for: You can set the flag FLAG_ACTIVITY_CLEAR_TOP to clear the back stack. The second flag FLAG_ACTIVITY_SINGLE_TOP avoid restarting the activity if used in combination with the flag mentioned before.

case android.R.id.home: {
    Intent intent = new Intent(this, HomeActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    startActivityIfNeeded(intent, 0);
    return true;
}

The intent needs to be passed using startActivityIfNeeded().



来源:https://stackoverflow.com/questions/18657192/how-to-enable-the-home-button-to-return-to-a-common-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!