自定义Radio-Group,添加" setOnCheckedChangeListener"

时间:2017-04-01 17:44:25

标签: android radio-group oncheckedchanged

好的,首先我有一个自定义无线电组,因为我需要不同的无线电组布局,例如3x3 radiogroup。

该课程如下:

public class CustomRadioButtons extends TableLayout implements OnClickListener{

private static final String TAG = "ToggleButtonGroupTableLayout";
private RadioButton activeRadioButton;

public CustomRadioButtons(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
}

public CustomRadioButtons(Context context, AttributeSet attrs) {
    super(context, attrs);
    // TODO Auto-generated constructor stub
}


@Override
public void onClick(View v) {
    final RadioButton rb = (RadioButton) v;
    if ( activeRadioButton != null ) {
        activeRadioButton.setChecked(false);
    }
    rb.setChecked(true);
    activeRadioButton = rb;
}

@Override
public void addView(View child, int index,
                    android.view.ViewGroup.LayoutParams params) {
    super.addView(child, index, params);
    setChildrenOnClickListener((TableRow)child);
}

@Override
public void addView(View child, android.view.ViewGroup.LayoutParams params) {
    super.addView(child, params);
    setChildrenOnClickListener((TableRow)child);
}

private void setChildrenOnClickListener(TableRow tr) {
    final int c = tr.getChildCount();
    for (int i=0; i < c; i++) {
        final View v = tr.getChildAt(i);
        if ( v instanceof RadioButton ) {
            v.setOnClickListener(this);
        }
    }
}

public int getCheckedRadioButtonId() {
    if ( activeRadioButton != null ) {
        return activeRadioButton.getId();
    }
    return -1;
}

public void resetGroup() {
    if ( activeRadioButton != null ) {
        activeRadioButton.setChecked(false);
    }
}

public String getCheckedRadioButtonText() {
    if ( activeRadioButton != null ) {
        return activeRadioButton.getText().toString();
    }
    return "";
}

}

在我的mainactivity中,我尝试使用内部类的CustomRadioButton(或者更准确地说,来自alertdialog),如下所示:

    final LayoutInflater[] inflater = {(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)};
    final View vi = inflater[0].inflate(R.layout.alertdialogxml, null);
    final CustomRadioButtons radioGroup = (CustomRadioButtons) vi.findViewById(R.id.radioGroup);

//this is how i would proceed (and it works) if this was a regular radioGroup.
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                //I wanna do Stuff Here.
            }
        });

所以我的问题是,在这种情况下如何设置OnCheckedChangeListner。我想我必须修改&#34; CustomRadioButtons&#34;上课,但我不知道如何。

感谢您的帮助! =)

0 个答案:

没有答案