[英]How to correctly use findViewById if a class A extends class B extends Activity
In Android, I have a class A which extends class B which extends an ActionBarActivity. 在Android中,我有一个类A,它扩展了类B,后者又扩展了ActionBarActivity。 Class A sets the content view.
A类设置内容视图。 For some reason, I'm unable to access the view elements from Class B. How can I access the view elements (ex: TextView)?
由于某种原因,我无法访问B类中的视图元素。如何访问视图元素(例如:TextView)? When I attempt to use findViewById in class B, it is always null.
当我尝试在类B中使用findViewById时,它始终为null。
public class A extends B {
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
}
}
public class B extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView myTextView = (TextView) findViewById(R.id.myTextView);
// myTextView is null
}
}
you're inheriting things backwards. 您正在向后继承事物。 Class B doesn't ever setContentView.
B类从来没有setContentView。
I think this is what you want: 我认为这是您想要的:
public class A extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
}
}
public class B extends A {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// A called setContentView(), so now we can find views by id.
TextView myTextView = (TextView) findViewById(R.id.myTextView);
// myTextView now is not null.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.