如何从 Java 中的另一个类获取变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14308956/
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
How do I get a variable from another class in Java?
提问by GrilledCheese
How do I set selectedPlayer to the value of position from my other class?
如何将 selectedPlayer 设置为我其他类的位置值?
I've read a bunch of similar questions on here, but I keep running into conflicts with my variables and functions.
我在这里阅读了一堆类似的问题,但我一直在与我的变量和函数发生冲突。
ScoreList.java
成绩单.java
public class ScoreList extends Activity {
Integer selectedPlayer = 0;
}
ScoreListAdapter.java
分数列表适配器.java
public class ScoreListAdapter extends ArrayAdapter<Score> {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final OnClickListener lsScoreView = new OnClickListener() {
@Override
public void onClick(View v) {
//send position to main class here
}
};
}
}
回答by Tony Chhabada
set selectedPlayer as static:
将 selectedPlayer 设置为静态:
public class ScoreList extends Activity {
static Integer selectedPlayer = 0;
}
This way,You can refer selecterPlayer using class name as it does not belong to any object of the class.
这样,您可以使用类名引用 selecterPlayer,因为它不属于该类的任何对象。
ScoreListAdapter.java
分数列表适配器.java
public class ScoreListAdapter extends ArrayAdapter<Score> {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final OnClickListener lsScoreView = new OnClickListener() {
@Override
public void onClick(View v) {
ScoreList.selectedPlayer;//You can use selectedPlayer here
}
};
}
}
回答by xagyg
Options...
选项...
Pass
ScoreList
in as a parameter to theScoreListAdapter
constructor and set it as an instance variable that you can refer to inScoreListAdapter.getView
.Pass
ScoreList
in as a parameter to thegetView
method.
ScoreList
作为参数传入ScoreListAdapter
构造函数并将其设置为实例变量,您可以在 中引用ScoreListAdapter.getView
。ScoreList
作为参数传入getView
方法。