存储单选按钮的整数值(Android Studio)

huangapple go评论74阅读模式
英文:

Store Radiobutton int value (Android Studio)

问题

> SCENARIO

在一个单选按钮组内有三个单选按钮,第一个单选按钮的名称是"A",第二个单选按钮的名称是"B",第三个单选按钮的名称是"C"。

> QUESTION

  1. 如何获取整数值?如果我选择第一个单选按钮,应该获得整数值2;类似地,如果我选择第二个和第三个单选按钮,应该获得整数值5和6。

  2. 一旦我选择了任何一个单选按钮,它会自动将整数值保存在共享偏好设置中(例如,我选择了第一个单选按钮,值为"2"会被存储)。

  3. 在我做出选择之后,我决定关闭应用程序,再次打开应用时,发现第一个单选按钮仍然被选中。

英文:

> SCENARIO

There 3 radiobuttons inside a radiogroup, first radiobutton name is "A", second radiobutton name is "B" and third radiobutton is "C".

> QUESTION

  1. How to get the int value that is if i select first radiobutton then it should get the int value of 2 and similarly if i select second and third radiobuttons then it should get the int value of 5 and 6.

  2. Once i select any of the radiobutton then it automatically saves the int value in shared preference (For example i choose first radiobutton that value "2" get stored).

  3. After i choose then i decided to close the app and open once again and see that first radiobutton is still selected.

答案1

得分: 1

你可以获取RadioGroup的CheckedId,然后将其与每个RadioButton的Id进行比较,然后根据值的位置进行设置。

示例:

int value;
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId){
        if (checkedId == R.id.buttonA) {
            value = 2;
        } else if (checkedId == R.id.buttonB) {
            value = 5;
        } else {
            value = 6;
        }
    }
});

将该值保存在您的首选项中,当您返回应用程序时,只需检查位置并执行radioGroup.check()

英文:

You can get the CheckedId of your RadioGroup and compare it with the Id from each RadioButton then set by the position of the values.

Example:

    int value;
    radioGroup.setOnCheckChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId){
            if (checkedId == R.id.buttonA) {
                value = 2;
            } else if (checkedId == R.id.buttonB) {
                value = 5;
            } else {
                value = 6;
            }
        }

Save that value on your preferences and when you get back to the app just check the position and do a radioGroup.check();

huangapple
  • 本文由 发表于 2020年10月6日 22:16:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/64227703.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定