Android Studio получает значения из переключателя и использует его в другом месте - PullRequest
0 голосов
/ 08 сентября 2018

У меня есть код ниже, чтобы использовать переключатель и получить значение и вернуть его в виде строки для функции. Надеюсь, что я мог бы использовать его в другом месте в основной программе. Однако это не так. это позволило бы мне использовать переменную btn, и если я сделал предложение atl-enter, объявив его final string [], оно вернет ноль. В большинстве онлайн-уроков и в стеке предыдущий вопрос включает в себя только поджаривание текста из выбранной кнопки в пределах onCheckedChanged.

public String listeneronbutton() {
        String btn;
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup);

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int checkedID) {
                int selectedId = radioGroup.getCheckedRadioButtonId();
                radioButton = (RadioButton) findViewById(checkedID);
                Toast.makeText(getApplicationContext(), radioButton.getText(), Toast.LENGTH_SHORT).show();
                btn = String.valueOf(radioButton.getText());      //(error here: variable 'btn' is accessed from within inner class, needs to be declared final)
            }
        });
        return btn;
}

Как мне получить функцию listeneronbutton(), способную правильно получить и вернуть btn значение?

Ответы [ 3 ]

0 голосов
/ 08 сентября 2018

у вас не может быть метода, который добавляет OnCheckedChangeListener и одновременно получает String (поскольку разделение обязанностей и один метод должны выполняться только один раз, другой метод чаще). аналогично этому вы можете добавить метод instanceRadioGroup() к onCreate() или onCreateView(), а затем получить текущее значение с помощью метода getButtonText().

также переменная int checkedId уже передается в область видимости, так что ее можно использовать.

/** the handle for the {@link RadioGroup} */
private RadioGroup mRadioGroup = null;

/** this field holds the button's text */
private String mButtonText = null;

/** the setter for the field */
protected void setButtonText(@Nullable String value) {
    this.mButtonText = value;
}

/** the getter for the field */
protected String getButtonText() {
    return this.mButtonText;
}

/** it sets mButtonText by checkedId */
protected void updateButtonText(int checkedId) {
    if ((checkedId == -1)) {
        this.setButtonText(null);
    } else {
        RadioButton radioButton = (RadioButton) this.mRadioGroup.findViewById(checkedId);
        this.setButtonText(radioButton.getText());
    }
}

/** this code should only run once, onCreate() or onCreateView() */
protected void instanceRadioGroup() {

    /* setting the handle for the {@link RadioGroup} */
    this.mRadioGroup = (RadioGroup) findViewById(R.id.radioGroup);

    /* update the field with the text of the default selection */
    int checkedId = this.mRadioGroup.getCheckedRadioButtonId();
    this.updateButtonText(checkedId);

    /* and also add an onCheckedChange listener */
    this.mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
            updateButtonText(checkedId);
        }
    });
}
0 голосов
/ 08 сентября 2018

Измените свой метод так:

public String listeneronbutton() {
    String btn;
    RadioGroup radioGroup =(RadioGroup)findViewById(R.id.radioGroup);
    int selectedId = radioGroup.getCheckedRadioButtonId();
    radioButton = (RadioButton) findViewById(checkedID);
    Toast.makeText(getApplicationContext(), radioButton.getText(), Toast.LENGTH_SHORT).show();
    btn = String.valueOf(radioButton.getText());      

    return btn;
}
0 голосов
/ 08 сентября 2018

Объявите String btn как поле. Таким образом, вы можете получить доступ в любом месте внутри класса.

public class Test{
    String btn;
    public String listeneronbutton(){

        return btn;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...