java从超类访问视图
我试图将处理导航抽屉的代码集中到一个所有活动都扩展的超类中。超级类本身扩展了活动,但我似乎不知道如何访问子类的视图(findviewbyid返回null)
如何从CommonCode访问CheckinActivity中膨胀的视图
超类oncreate:
public class CommonCode extends Activity{
....
@Override
public void onCreate(Bundle b){
super.onCreate(b);
context=getBaseContext();
子类
public class CheckInActivity extends CommonCode {
@Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_main);
}
# 1 楼答案
我要做的是为每个子活动提供单独的xml,但导航抽屉的所有xml ID都是相同的
接下来,当您启动扩展活动的任何子类时,传递一个带有contextView id-R.layout的包。MY_SUB_活动-在一个捆绑包中,并实际设置超级类中每个子活动的内容视图
之后,您可以使用findViewByID查找抽屉,在超类中设置它们,然后从自己的类中处理子类的视图
您的视图可能会返回null,因为您在运行子类的onCreate之前运行了超类的onCreate,因此尚未调用setContentView(因此findViewByID将不起作用)
编辑:
此外,您不必为所有导航抽屉ID命名相同的名称,我只是认为使用
<include>
标记更容易,以最小化xml文件中的冗余例如:
亚类-
超类: