如何从“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;
}
}
答案 0 :(得分:2)
如果您想要访问课程somevariable
中定义的特定ParentActivity
,那么您应该尝试将其作为ParentActivity.somevariable
访问,因为它已声明为static
:
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 ;)
}
}
答案 1 :(得分:0)
你可以像这样传递变量:
public void doSomething(String someVariable){
b = someVariable;
}
答案 2 :(得分:0)
a = ParentActivity.somevarible;
应该有用。