我想访问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
}
答案 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.onCreate
中MainActivity
之后的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
。