如何从spinner监听器访问变量?

时间:2017-07-19 08:03:18

标签: 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
            }
        });

我试图在方法之外声明变量但是这会给出错误'Variable'selectedTeam'是从内部类中访问的,需要声明为final'。我尝试过,但由于最终的字符串无法更改,因此无效。

4 个答案:

答案 0 :(得分:2)

改为使用班级成员

JLS 8.1.3. Inner Classes and Enclosing Instances中:

  

当一个内部类(其声明不在静态中发生)   context)指的是作为a的成员的实例变量   词汇封闭类,词汇对应的变量   使用封闭实例。

     

使用了任何局部变量,形式参数或异常参数但是   未在内部类中声明必须声明为final。

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

[...]
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
            }
        }
    });

答案 1 :(得分:1)

您需要将变量声明为全局。

public class MainActivity extends AppCompatActivity {

String selectedteam;
...
buttonApply.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View v) {
            String editedName = editText.getText().toString();
            selectedteam = editedName; // or whatever you want
        }
    });

答案 2 :(得分:0)

在我的情况下,我使用共享首选项来存储值,并在我想要使用的地方获取该值。

SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "selectedTeam");
editor.apply();

如何获得价值

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
String restoredText = prefs.getString("name", null);

希望有所帮助

答案 3 :(得分:0)

你需要以不同的方式做到这一点。 这项工作对我来说,我使用AdapterView.OnItemSelectedListener和View.OnClickListener实现了活动并覆盖了方法。

您现在可以从OnClick方法访问selectedTeam。

(如果您使用xml文件,请考虑更改应用程序的包)

<强> MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener,View.OnClickListener{

    Spinner sTeam;
    EditText editText;
    Button button;
    String selectedTeam;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sTeam = (Spinner) findViewById(R.id.spinner_team);
        button = (Button) findViewById(R.id.confirmation_button);
        editText = (EditText) findViewById(R.id.edittext_team);


        List<String> spinnerArray =  new ArrayList<String>();
        spinnerArray.add("team1");
        spinnerArray.add("team2");
        spinnerArray.add("team3");

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                this, android.R.layout.simple_spinner_item, spinnerArray);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sTeam.setAdapter(adapter);

        button.setOnClickListener(this);
        sTeam.setOnItemSelectedListener(this);
    }

    @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) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case (R.id.confirmation_button) :{
                //You can access to selected team here
            }break;
        }
    }


}

<强> activity_main.xml中

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.yourpackage.test">

    <Spinner
        android:id="@+id/spinner_team"
        android:layout_width="368dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="16dp"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/confirmation_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:layout_marginTop="8dp"
        app:layout_constraintTop_toBottomOf="@+id/edittext_team"
        app:layout_constraintLeft_toRightOf="@+id/edittext_team"
        android:layout_marginLeft="8dp" />

    <EditText
        android:id="@+id/edittext_team"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Name"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/spinner_team" />

</android.support.constraint.ConstraintLayout>