【问题标题】:Toolbar home button not working if there is no option menu如果没有选项菜单,工具栏主页按钮不起作用
【发布时间】:2015-01-06 13:50:19
【问题描述】:

在将新的Toolbar 与 appcompat 支持库一起使用时,在我看来,除非您设置了有效的选项菜单,否则 Home 按钮无法像以前那样工作。一个简单的标准活动:

public class MyActivity extends ActionBarActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.some_page);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    ActionBar bar = getSupportActionBar();
    bar.setHomeButtonEnabled(true);
    bar.setDisplayHomeAsUpEnabled(true);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // getMenuInflater().inflate(R.menu.some_menu, menu);
    return super.onCreateOptionsMenu(menu);
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        onBackPressed() or finish() or whatever();
        break;
    }
    return super.onOptionsItemSelected(item);
  }
}

如果在onCreateOptionsMenu() 中设置了菜单,则onOptionsItemSelected() 将被调用android.R.id.home,一切都很好。但是,如果根本没有onCreateOptionsMenu()(或者它是空的,或者返回true或者调用super函数),则根本不会调用onOptionsItemSelected(),因此没有机会捕捉到点击在主页按钮上。我什至尝试将一个空菜单传递给onCreateOptionsMenu(),但没有帮助。

是否有一种解决方法可以让我们在不需要功能选项菜单的页面上使用有效的主页按钮?

【问题讨论】:

标签: android toolbar android-appcompat


【解决方案1】:

你可以试试这个..

toolbar.setNavigationOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent =new Intent(Context,<Destination activity);
startActivity(intent);
}
});

希望对你有所帮助..

【讨论】:

    猜你喜欢
    • 2017-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-24
    • 2013-03-28
    • 1970-01-01
    相关资源
    最近更新 更多