programing

Android에서 선택한 RadioGroup 인덱스를 가져오는 방법

procenter 2022. 8. 10. 21:49
반응형

Android에서 선택한 RadioGroup 인덱스를 가져오는 방법

Android에서 선택한 RadioGroup 인덱스를 쉽게 가져올 수 있는 방법이 있습니까? 아니면 변경을 듣고 마지막으로 선택한 인덱스를 유지하기 위해 OnCheckedChangeListener를 사용해야 합니까?

xml의 예:

<RadioGroup android:id="@+id/group1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical">
    <RadioButton android:id="@+id/radio1" android:text="option 1" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio2" android:text="option 2" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio3" android:text="option 3" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio4" android:text="option 4" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio5" android:text="option 5" android:layout_width="wrap_content" android:layout_height="wrap_content" />
</RadioGroup>

사용자가 선택한 경우option 3나는 지수를 얻고 싶다, 2.

다음과 같은 작업을 수행할 수 있습니다.

int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
View radioButton = radioButtonGroup.findViewById(radioButtonID);
int idx = radioButtonGroup.indexOfChild(radioButton);

이 경우,RadioGroup기타 뷰 포함(예:TextView)이후,indexOfChild()메서드가 잘못된 인덱스를 반환합니다.

선택한 항목을 가져오려면RadioButton에 있는 텍스트RadioGroup:

 RadioButton r = (RadioButton) radioButtonGroup.getChildAt(idx);
 String selectedtext = r.getText().toString();

이거면 될 거야

int index = myRadioGroup.indexOfChild(findViewById(myRadioGroup.getCheckedRadioButtonId()));

라디오 그룹에 대한 참조를 가지고getCheckedRadioButtonId ()체크된 라디오 버튼 ID를 가져옵니다.여기를 보세요

RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radio_group);

선택한 무선 옵션을 사용할 필요가 있는 경우.

int checkedRadioButtonId = radioGroup.getCheckedRadioButtonId();
if (checkedRadioButtonId == -1) {
    // No item selected
}
else{
    if (checkedRadioButtonId == R.id.radio_button1) {
        // Do something with the button
    }
}

이거 먹어봐

        RadioGroup  group= (RadioGroup) getView().findViewById(R.id.radioGroup);
        group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                View radioButton = radioGroup.findViewById(i);
                int index = radioGroup.indexOfChild(radioButton);
            }
        });

OnChecked Change Listener 를 사용하거나 getChecked Radio Button Id() 를 사용할 수 있습니다.

다음을 사용할 수 있습니다.

RadioButton rb = (RadioButton) findViewById(rg.getCheckedRadioButtonId());

//선택한 항목의 ID를 가져오는 데 사용합니다.

int selectedID = myRadioGroup.getCheckedRadioButtonId();

//선택한 항목의 보기를 가져옵니다.

View selectedView = (View)findViewById( selectedID);

이런 식으로 완벽하게 작동했습니다.

    RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radio_group);
    int radioButtonID = radioGroup.getCheckedRadioButtonId();
    RadioButton radioButton = (RadioButton) radioGroup.findViewById(radioButtonID);
    String selectedtext = (String) radioButton.getText();

먼저 RadioButton에 값을 설정하기만 하면 됩니다.다음은 예를 제시하겠습니다.

RadioButton radioButton = (RadioButton)findViewById(R.id.radioButton);      
radioButton.setId(1);        //some int value

그리고 이 spacific radioButton이 선택될 때마다 당신이 지정한 Id에 의해 그 값을 끌어낼 수 있습니다.

RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radioGroup);                     
int whichIndex = radioGroup.getCheckedRadioButtonId(); //of course the radioButton
                                                       //should be inside the "radioGroup"
                                                       //in the XML

건배!

radioSexGroup=(RadioGroup)findViewById(R.id.radioGroup);

  btnDisplay=(Button)findViewById(R.id.button);

  btnDisplay.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
        int selectedId=radioSexGroup.getCheckedRadioButtonId();
        radioSexButton=(RadioButton)findViewById(selectedId);
        Toast.makeText(MainActivity.this,radioSexButton.getText(),Toast.LENGTH_SHORT).show();
     }
  });

코틀린:

val selectedIndex = radioButtonGroup?.indexOfChild(
  radioButtonGroup?.findViewById(
    radioButtonGroup.getCheckedRadioButtonId())
)

파티에 늦었지만, 여기 @Tarek360의 Kotlin의 답변이 간략화되어 있습니다.RadioGroup비 RadioButtons를 포함할 수 있습니다.

    val RadioGroup.checkedIndex: Int
        get() = children
            .filter { it is RadioButton }
            .indexOfFirst { it.id == checkedRadioButtonId }

만약 당신이...RadioFroup확실히 가지고 있는 것은RadioButtons 이것은 다음과 같이 단순할 수 있습니다.

    private val RadioGroup.checkedIndex = 
        children.indexOfFirst { it.id == checkedRadioButtonId }

그럼 당신은 그 비용을 부담하지 않아도 되겠네요.findViewById.

 int index_selected = radio_grp.indexOfChild(radio_grp
                .findViewById(radio_grp.getCheckedRadioButtonId()));

이것만 사용해 주세요.

    int index = 2;
    boolean option3Checked = radioGroup.getCheckedRadioButtonId() == radioGroup.getChildAt(2).getId();

그룹에 TextView 또는 RadioButton이 없는 경우에도 올바른 위치를 얻을 수 있는 Kotlin 내선번호입니다.

fun RadioGroup.getCheckedRadioButtonPosition(): Int {
    val radioButtonId = checkedRadioButtonId
    return children.filter { it is RadioButton }
        .mapIndexed { index: Int, view: View ->
            index to view
        }.firstOrNull {
            it.second.id == radioButtonId
        }?.first ?: -1
}

할수있습니다

findViewById

라디오 그룹으로부터.

다음은 샘플입니다.

((RadioButton)my_radio_group.findViewById(R.id.radiobtn_veg)).setChecked(true);

간단하게 할 수 있습니다.

- 무선 그룹 및 라디오 버튼을 onCreate 메서드에서 제외합니다.

private RadioGroup GrupName;
private RadioButton NameButton;

- onCreate 메서드로 뷰 ID 설정

GrupName = (RadioGroup) findViewById(R.id.radioGroupid);

- 다음을 사용하여 선택한 라디오 버튼 ID를 가져옵니다.

int id = GroupName.getCheckedRadioButtonId();

- id를 사용하여 버튼 선택 뷰와 일치시킵니다.

NameButton = (RadioButton) findViewById(id);

- 라디오 버튼 값을 가져옵니다.

String valueExpected = NameButton.getText().toString();

--- PS: INT 값을 원하는 경우 캐스팅할 수 있습니다.

int valueExpectedIn = Integer.parseInt(valueExpected);
radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // get selected radio button from radioGroup
            int selectedId = radioSexGroup.getCheckedRadioButtonId();
            // find the radiobutton by returned id
            radioSexButton = (RadioButton) findViewById(selectedId);
Toast.makeText(MainActivity.this,radioSexButton.getText(),Toast.LENGTH_SHORT).show();
        }
    });

각 라디오 버튼에 ID가 이미 할당되어 있습니다.케이스 블록을 사용하면 선택한 옵션버튼을 수동으로 검출할 수 있습니다.또한 OnChecked Change Listener를 사용하여 검출할 수도 있습니다.

xml:

    <RadioGroup
        android:id="@+id/rd_group_pick_reason"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toBottomOf="@id/ti_titel"
        android:orientation="horizontal"
        android:paddingHorizontal="16dp"
        >
        <com.google.android.material.radiobutton.MaterialRadioButton
            android:id="@+id/rd_not_deliverable"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:text="@string/txt_not_deliverable"
            android:checked="true"
            />

        <com.google.android.material.radiobutton.MaterialRadioButton
            android:id="@+id/rd_after_pack"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:text="@string/txt_after_pack"
            />
    </RadioGroup>

자바:

final RadioGroup radioGroup = dialogView.findViewById(R.id.rd_group_pick_reason);    
switch (radioGroup.getCheckedRadioButtonId()) {
    case R.id.rd_not_deliverable:
        // TODO
    break;
    case R.id.rd_after_pack:
        // TODO
    break;
}

또는

radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
    switch (group.getCheckedRadioButtonId()) {
        case R.id.rd_not_deliverable:
            System.out.println("not deliverable");
            break;
        case R.id.rd_after_pack:
            System.out.println("after pack");
            break;
    }

언급URL : https://stackoverflow.com/questions/6440259/how-to-get-the-selected-index-of-a-radiogroup-in-android

반응형