Android ListView with RadioButton in singleChoice mode and a custom row layout

前端 未结 7 1947
野趣味
野趣味 2020-12-06 04:13

I have a ListView, which is in singleChoice mode. All I want is to display a RadioButton to the side, that when clicked highlights to say i

7条回答
  •  爱一瞬间的悲伤
    2020-12-06 04:58

    Simple solution:

    Add this line in the RadioButton layout of your xml file:

    
    

    Then in the activity class that uses the ListView, add the following:

       private RadioButton listRadioButton = null;
       int listIndex = -1;
    
       public void onClickRadioButton(View v) {
            View vMain = ((View) v.getParent());
            // getParent() must be added 'n' times, 
            // where 'n' is the number of RadioButtons' nested parents
            // in your case is one.
    
            // uncheck previous checked button. 
            if (listRadioButton != null) listRadioButton.setChecked(false);
            // assign to the variable the new one
            listRadioButton = (RadioButton) v;
            // find if the new one is checked or not, and set "listIndex"
            if (listRadioButton.isChecked()) {
                listIndex = ((ViewGroup) vMain.getParent()).indexOfChild(vMain); 
            } else {
                listRadioButton = null;
                listIndex = -1;
            }
        }
    

    With this simple code only one RadioButton is checked. If you touch the one that is already checked, then it returns to the unchecked mode.

    "listIndex" is tracking the checked item, -1 if none.

    If you want to keep always one checked, then code in onClickRadioButton should be:

       public void onClickRadioButton(View v) {
            View vMain = ((View) v.getParent());
            int newIndex = ((ViewGroup) vMain.getParent()).indexOfChild(vMain);
            if (listIndex == newIndex) return;
    
            if (listRadioButton != null) {
                    listRadioButton.setChecked(false);
            }
            listRadioButton = (RadioButton) v;
            listIndex = newIndex; 
        }
    

提交回复
热议问题