如何从 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:50:13  来源:igfitidea点击:

How do I get a variable from another class in Java?

javaandroidclassvariables

提问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...

选项...

  1. Pass ScoreListin as a parameter to the ScoreListAdapterconstructor and set it as an instance variable that you can refer to in ScoreListAdapter.getView.

  2. Pass ScoreListin as a parameter to the getViewmethod.

  1. ScoreList作为参数传入ScoreListAdapter构造函数并将其设置为实例变量,您可以在 中引用ScoreListAdapter.getView

  2. ScoreList作为参数传入getView方法。