Получение индекса выбранной RadioButton

336
05 мая 2018, 17:55

Есть следующая разметка:

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/text1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="МАТРИЦА ВЫБОРА ПРОФЕССИИ"
            android:textColor="#000000"
            android:textSize="24sp" />
        <TextView
            android:id="@+id/text2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/text1"
            android:layout_margin="10dp"
            android:text="@string/test1text"
            android:textColor="#000000"
            android:textSize="20sp" />
        <TextView
            android:id="@+id/text3"
            android:layout_below="@id/text2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:background="@drawable/border"
            android:gravity="center"
            android:text="СФЕРА ТРУДА"
            android:textColor="#000000"
            android:textSize="20sp"/>
        <RadioGroup
            android:id="@+id/rg1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/text3"
            android:layout_margin="5dp">
            <RadioButton
                style="@style/RadioButton"
                android:text="Человек"/>
            <RadioButton
                style="@style/RadioButton"
                android:text="Информация"/>
            <RadioButton
                style="@style/RadioButton"
                android:text="Финансы"/>
            <RadioButton
                style="@style/RadioButton"
                android:text="Техника" />
            <RadioButton
                style="@style/RadioButton"
                android:text="Искусство"/>
            <RadioButton
                style="@style/RadioButton"
                android:text="Животные"/>
            <RadioButton
                style="@style/RadioButton"
                android:text="Растения"/>
            <RadioButton
                style="@style/RadioButton"
                android:text="Продукты питания"
                />
            <RadioButton
                style="@style/RadioButton"
                android:text="Изделия"/>
            <RadioButton
                style="@style/RadioButton"
                android:text="Природные ресурсы"/>
        </RadioGroup>
        <TextView
            android:id="@+id/text4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:background="@drawable/border"
            android:gravity="center"
            android:text="ВИД ТРУДА"
            android:textColor="#000000"
            android:textSize="20sp"
            android:layout_below="@id/rg1"/>
        <RadioGroup
            android:id="@+id/rg2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/text4"
            android:layout_margin="5dp">
            <RadioButton
                style="@style/RadioButton"
                android:text="Управление"/>
            <RadioButton
                style="@style/RadioButton"
                android:text="Обслуживание"/>
            <RadioButton
                style="@style/RadioButton"
                android:text="Образование"/>
            <RadioButton
                style="@style/RadioButton"
                android:text="Оздоровление"/>
            <RadioButton
                style="@style/RadioButton"
                android:text="Творчество"/>
            <RadioButton
                style="@style/RadioButton"
                android:text="Производство"/>
            <RadioButton
                style="@style/RadioButton"
                android:text="Конструирование"/>
            <RadioButton
                style="@style/RadioButton"
                android:text="Исследование питания"/>
            <RadioButton
                style="@style/RadioButton"
                android:text="Защита"/>
            <RadioButton
                style="@style/RadioButton"
                android:text="Контроль"/>
        </RadioGroup>
        <Button
            android:onClick="onClick"
            android:id="@+id/bt2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/rg2"
            android:text="РЕЗУЛЬТАТ"
            android:textSize="20sp" />
        <TextView
            android:id="@+id/text5"
            android:background="@drawable/border"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/bt2"
            android:textAllCaps="true"
            android:textSize="25sp"/>
    </RelativeLayout>
</android.support.v4.widget.NestedScrollView>

И код:

//... 
static int x, y = -1;
//...
@Override
    protected void onResume() {
        super.onResume();
        RadioGroup radioGroup1 = (RadioGroup) findViewById(R.id.rg1);
        radioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                y = checkedId;
                Toast toast = Toast.makeText(getApplicationContext(),
                        String.valueOf(y), Toast.LENGTH_SHORT);
                toast.show();
            }
        });
        RadioGroup radioGroup2 = (RadioGroup) findViewById(R.id.rg2);
        radioGroup2.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                x = checkedId;
                Toast toast = Toast.makeText(getApplicationContext(),
                        String.valueOf(x), Toast.LENGTH_SHORT);
                toast.show();
            }
        });
}

Вот только во втором случае (RadioGroup2), при показе ID выбранного элемента он учитывает предыдущую радиогруппу, и выдает число из диапазона [11;20], вместо требуемых [1;10]. В чем ошибка?

READ ALSO
Как проигрывать звук из mp4 видео?

Как проигрывать звук из mp4 видео?

Каким образом можно проиграть звуковую дорожку видеофайла (mp4) при помощи java? И как её можно остановить/поставить на паузу/перескочить на определённое...

239
Не рисуются фигуры на JFrame(JPanel) при Layout(null)

Не рисуются фигуры на JFrame(JPanel) при Layout(null)

Нужно, чтобы на одном JFrame отображались кнопки и фигуры(стрелки/линии)Для расположения кнопок задаю layout null, но при этом не отрисовываются элементы...

214
Как можно заполнить контейнер для Tab?

Как можно заполнить контейнер для Tab?

Хочу сделать tab-s в NavigationActivityИ чтоб прокручивать со свайпом

249
Как сделать так, чтобы появлялось одно уведомление, а через интервал уже другое? (Android Java)

Как сделать так, чтобы появлялось одно уведомление, а через интервал уже другое? (Android Java)

Пытаюсь сделать уведомления в Android StudioМне нужно сделать так, чтобы сначала появилось одно уведомление, затем, минуя один интервал, появилось...

288