프로그래밍 방식으로 RadioGroups 및 중첩 된 RadioButton을 사용하고 있습니다. 일부 동작을위한 라디오 버튼 만들기 및 제거. 그러나 문제가 공개되었을 때, 나는 onCheckedChanged
이벤트를 발동했다. RadioGroup의 모든 라디오 버튼을 제거하고 RG를 제거한 후에도 시스템에서 라디오 버튼 카운터를 재설정하지 않습니다. 이 충돌은 특정 radioButton을 검사하는 등의 이벤트를 잡으려고 할 때 발생하지만 라디오 버튼 (checkId)의 인덱스가 실제 상태와 같지 않기 때문에 널 포인트 예외가 발생합니다. radioButton을 직접 계산하고 onCheckedChanged 이벤트에서 checkId를 수정해야합니까? 마치 목발 모양입니다. 여기RadioGroup checkedId (또는 getCheckedRadioButtonId())가 올바르게 작동하지 않습니다.
일부 코드 예제 :
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);
}
}
로그 캣 여기 :
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
감사합니다. –