Android中ActionBar和ToolBar添加返回箭头的实例代码

时间:2019-04-06
本文章向大家介绍Android中ActionBar和ToolBar添加返回箭头的实例代码,主要包括Android中ActionBar和ToolBar添加返回箭头的实例代码使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

 1.ActionBar添加返回箭头

//onCreate方法中
ActionBar actionBar = this.getSupportActionBar();
actionBar.setTitle("搜索功能");
actionBar.setDisplayHomeAsUpEnabled(true);
//activity类中的方法
@Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId() == android.R.id.home)
    {
      finish();
      return true;
    }
    return super.onOptionsItemSelected(item);
  }

在这里,ActionBar引入包:import android.support.v7.app.ActionBar;

2. ToolBar添加返回箭头

代码如下:

//onCreate函数中
Toolbar mToolbarTb = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbarTb);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//activity类中的方法
//添加点击返回箭头事件
@Override
public boolean onOptionsItemSelected(MenuItem item) {
  if(item.getItemId() == android.R.id.home)
  {
    finish();
    return true;
  }
  return super.onOptionsItemSelected(item);
}

总结

以上所述是小编给大家介绍的Android中ActionBar和ToolBar添加返回箭头的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!