如何从“OtherClass”中获取“somevariable”的值?我可以/应该像我在下面尝试的那样使用 Activity 的上下文吗?
public class ParentActivity extends Activity {
//This variable is reused by multiple Activities inheriting form this class
protected static String somevariable = "text";
...
}
public class MyActivity extends ParentActivity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
myObject = new OtherClass(this);
myObject.doSomething();
...
}
...
}
public class OtherClass(){
private Context c;
private String b;
OtherClass(Context context) {
c = context;
}
doSomething() {
// This does NOT work.
// How can I get somevariable from the ParentActivity????
b = c.somevariable;
}
}
最佳答案
如果您想访问在类 ParentActivity
中定义的特定 somevariable
那么您应该尝试以 ParentActivity.somevariable
的形式访问它,因为它是声明静态
:
public class OtherClass { // Why were there extra parentheses ()
private Context c;
private String b;
OtherClass(Context context) {
c = context;
}
doSomething(){
b = ParentActivity.somevariable; // Try this at home ;)
}
}
关于java - 类如何从其包含复合类的父类(扩展 Activity)引用变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12552358/