java - 如何从微调监听器访问变量?

标签 java android

我有以下代码,我想在其中访问按钮监听器中的“selectedTeam”。

        //Adding setOnItemSelectedListener method on spinner.
        sTeams.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                selectedTeam = parent.getItemAtPosition(position).toString();
                editText.setText(selectedTeam, TextView.BufferType.EDITABLE);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        buttonApply.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                String editedName = editText.getText().toString();
                // Here I want to access selectedTeam
            }
        });

我试图在方法外部声明变量,但这给出了错误“变量‘selectedTeam’是从内部类中访问的,需要声明为最终的”。我试过了,但这不起作用,因为无法更改最终字符串。

最佳答案

改用类成员

JLS 8.1.3. Inner Classes and Enclosing Instances :

When an inner class (whose declaration does not occur in a static context) refers to an instance variable that is a member of a lexically enclosing class, the variable of the corresponding lexically enclosing instance is used.

Any local variable, formal parameter, or exception parameter used but not declared in an inner class must be declared final.

这意味着您只能在匿名 内部使用外部 final 变量或封闭类成员类。

[...]
private String selectedTeam;
[...]

//Adding setOnItemSelectedListener method on spinner.
    sTeams.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                                   int position, long id) {
            selectedTeam = parent.getItemAtPosition(position).toString();
            editText.setText(selectedTeam, TextView.BufferType.EDITABLE);
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    buttonApply.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View v) {
            String editedName = editText.getText().toString();
            if (selectedTeam != null && !"".equals(selectedTeam)) {
                // Do something
            }
        }
    });

关于java - 如何从微调监听器访问变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45184445/

相关文章:

java - css 找到图像但无法将它们加载到预览中

android - android 中 shapes.xml 中的多个形状

java - 如何将字符串转换为时区 : Android

android - Ionic Serve 工作正常但运行 android 失败

java - 我正在尝试使用 getter 和 setter 从我的 firebase 数据库中检索数据,但收到错误消息说无法转换对象

java - 为什么我在第 3 条和第 4 条打印语句中返回整数而不是字符?

java - 使用Java将包含文件的目录上传到S3

android - gradle导入会突然失败吗?

android - 如何获得相机的反馈?

java - Lagom Cassandra 驱动程序