如何在Android的Activity中访问BaseActivity ToolBar

时间:2018-11-10 08:23:59

标签: android

我想访问MyActivity中扩展了BaseActivity的toolBar,可以访问MainActivity中的Toolbar。

BaseActivity

  public abstract class BaseActivity extends AppCompatActivity{
    @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            setContentView(R.layout.fragment_container_base);
            Toolbar toolBar = (Toolbar) findViewById(R.id.tool_bar);
    }
    }

MyActivity

 public class MyActivity extends BaseActivity {
     @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
       // here i want to access BaseActivity  Toolbar
    }

1 个答案:

答案 0 :(得分:1)

BaseActivity的{​​{3}}中设置工具栏:

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.fragment_container_base);
   Toolbar toolBar = (Toolbar) findViewById(R.id.tool_bar);
   setSupportActionBar(toolbar);
}

然后从super.onCreateMainActivity之后的setSupportActionBar获取工具栏:

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   ActionBar actionBar = getSupportActionBar();
}

您不能将ActionBar强制转换为Toolbar,但是如果您确实要访问工具栏,则将其更改为实例变量:

protected Toolbar toolbar;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_container_base);
    toolBar = (Toolbar) findViewById(R.id.tool_bar);
    // ...

使用protected修饰符,您可以访问toolbar中的MainActivity