Android - actionBar.setDisplayHomeAsUpEnabled问题

时间:2013-03-02 10:03:15

标签: android android-actionbar actionbarsherlock android-fragmentactivity

在我的延伸SherlockFragmentActivity的活动中,我有动作栏并且还设置了actionBar.setDisplayHomeAsUpEnabled(true)以回到我之前的活动。一切正常。但是当我点击主页按钮时,背景颜色应仅应用于应用程序图标,但它也适用于操作栏上的“标题”,如屏幕截图所示。我不希望这种情况发生。当我点击主页按钮时,只有应用程序图标可以点击(应该只为应用程序图标应用背景颜色)而不是标题。知道我该怎么办?

enter image description here

我的活动代码:

ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle(some_string);

2 个答案:

答案 0 :(得分:16)

不要忘记这部分,因为主页按钮也是一个MENU按钮。

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            // This is called when the Home (Up) button is pressed in the action bar.
            // Create a simple intent that starts the hierarchical parent activity and
            // use NavUtils in the Support Package to ensure proper handling of Up.
            Intent upIntent = new Intent(this, MainActivity.class);
            if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
                // This activity is not part of the application's task, so create a new task
                // with a synthesized back stack.
                TaskStackBuilder.from(this)
                        // If there are ancestor activities, they should be added here.
                        .addNextIntent(upIntent)
                        .startActivities();
                finish();
            } else {
                // This activity is part of the application's task, so simply
                // navigate up to the hierarchical parent activity.
                NavUtils.navigateUpTo(this, upIntent);
            }
            return true;
    }
    return super.onOptionsItemSelected(item);
}

答案 1 :(得分:1)

标准的Android UI模式是将标题包含在按下状态。 但是,我想如果您按照此链接(描述如何在操作栏的左侧添加自定义视图)How to align items in action bar to the left?,并将标题设置为空。以下代码适用于我的本地设备

ActionBar action=getActionBar();
action.setDisplayShowCustomEnabled(true);
action.setHomeButtonEnabled(true);
action.setDisplayShowTitleEnabled(false);
TextView title =new TextView(getApplicationContext());
title.setText("Your Title here");
title.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);
action.setCustomView(title);