Android 从另一个类访问主要活动变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10568585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android access main activity variables from another class
提问by Co Koder
I have a main activity class and find class. I need to access variable of main activity variable's that is "name" from find class. I tried to access with below snippet code but I get an error. How can I access main activity variables from another class ?
我有一个主要的活动课程并找到课程。我需要从 find 类访问主要活动变量的变量,即“名称”。我尝试使用以下代码段进行访问,但出现错误。如何从另一个类访问主要活动变量?
public class main extends Activity {
public static String name=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1=(Button)findViewById(R.id.button1);
final EditText edittext = (EditText) findViewById(R.id.editText1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
name=edittext.getText().toString();
}
});
}
My second class....
我的第二堂课……
public class find {
public void finder(){
main mainactivity=new main();
String incoming_name =mainactivity.name;//I can not use like that ?
// do something
}
}
}
回答by Barak
1) You shouldn't instantiate an activity, intents start activities
1)你不应该实例化一个活动,意图开始活动
2) You have declared the variable public static
, so you can simply reference it (without instantiating the class) by main.name
...
2)您已经声明了变量public static
,因此您可以通过以下方式简单地引用它(无需实例化类)main.name
...
回答by MByD
You don't want to access Activity
's variables directly from another (outer) class. This is a bad practice, as Activities are, after all, part of the UI, and not the backend of the application.
您不想Activity
直接从另一个(外部)类访问的变量。这是一个不好的做法,因为活动毕竟是 UI 的一部分,而不是应用程序的后端。
Also, note that in your example, the name
property is static
and doesn;t belong to a specific instance.
另请注意,在您的示例中,该name
属性属于static
和不属于特定实例。