RadioGroup checkedId(或 getCheckedRadioButtonId())工作不正确

RadioGroup checkedId (or getCheckedRadioButtonId()) works incorrect

我正在以编程方式使用 RadioGroups 和嵌套的 RadioButtons。为某些行为创建和删除单选按钮。但是当我触发 onCheckedChanged 事件时,问题就暴露了。系统不会重置单选按钮计数器,即使在我删除 radioGroup 中的所有单选按钮之后,甚至在删除 RG 之后也是如此。 当我试图捕捉事件时发生这种冲突,例如检查特定的单选按钮,但我得到空点异常,因为单选按钮的索引 (checkId) 不等于真实状态。 我应该自己计算 radioButtons 并在 onCheckedChanged 事件中更正 checkId 吗? 看起来像拐杖。

这里有一些代码示例:

private static final String TAG = MainActivity.class.getSimpleName();
private RadioGroup rg;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    LinearLayout ll = findViewById(R.id.someLL);
    rg = new RadioGroup(this);
    rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            Log.d(TAG, "checked id: " + checkedId);
            Log.d(TAG, "print text: " + ((RadioButton) group.getChildAt(checkedId)).getText() );
        }
    });
    ll.addView(rg);

    rebuildRG(Arrays.asList("one", "two", "three", "four", "five"));

    rg.removeAllViews();

    rebuildRG(Arrays.asList("111", "222", "333", "444"));
}

private void rebuildRG(List<String> data){
    for(String i: data){
        RadioButton rb = new RadioButton(this);
        rb.setText(i);
        rg.addView(rb);
    }
}

Logcat 这里:

D/MainActivity: checked id: 9
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.flexdecision.ak_lex.radiogroup, PID: 11604
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.RadioButton.getText()' on a null object reference

您正在尝试使用 checkedId 作为位置。请参阅下面的行。

((RadioButton) group.getChildAt(checkedId))

它在回调中明确提到它是 ID 而不是 position。见。

@Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
      //checkedId :- xml id of currently checked radio Button   
    }

getChildAt(int index) :- getChildAt() takes index as argument not ID

解决方案是

 ((RadioButton) group.findViewById(checkeId)).getText();

或者简单地说。

((RadioButton)findViewById(checkeId)).getText();