在每个活动上调用工具栏 [英] Calling Toolbar on each Activity

查看:77
本文介绍了在每个活动上调用工具栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序有一个工具栏,该工具栏应出现在每个视图上.目前,我在onCreate()方法中针对我拥有的每个活动执行以下操作:

My app has a toolbar that should be present on every view. Currently, I do the following in my onCreate() method for each Activity I have:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

是否需要在每个Activity的每个onCreate()方法中执行此操作,还是有更简单的方法?另外,作为附带的问题,我如何在工具栏中实现后退"功能,如果用户单击该操作,该功能会将用户撤回一项操作?

Does this need to be done in every onCreate() method in every Activity or is there a simpler way? Also, as a side question, how can I implement a "back" feature in the toolbar that takes the user back one action if they click it?

推荐答案

Activity

Create a Base class for Activity

public abstract class BaseActivity extends AppCompatActivity {

  Toolbar toolbar;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(getLayoutResource());
    configureToolbar();
  }

  protected abstract int getLayoutResource();

  private void configureToolbar() {
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {
      setSupportActionBar(toolbar);
      getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        FragmentManager fm = getSupportFragmentManager();
        if (fm != null && fm.getBackStackEntryCount() > 0) {
          fm.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
        } else {
          finish();
        }
        return true;
      default:
        return super.onOptionsItemSelected(item);
    }
  }
}

,然后在每个Activity中扩展此BaseActivity以获得ToolBar并实现后退功能.

And in each Activity extends this BaseActivity to get the ToolBar and implementing the back feature.

最后不要忘了在每个活动layout中加入ToolBar.

At last don't forget to include the ToolBar in each activity layout.

在每个Activity中覆盖该方法getLayoutResource()并传递布局ID.

Override that method getLayoutResource() in each Activity and pass the layout id.

public class MainActivity extends BaseActivity {

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

  @Override
  public int getLayoutResource() {
    return R.layout.activity_main;
  }

这篇关于在每个活动上调用工具栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆