我找到了解決方案here和here。
基本上,我們必須創建一個「Checkable」佈局,因爲視圖的根項目必須實現Checkable接口。
所以我創建了一個可以掃描RadioButton和voilá的RelativeLayout包裝器,這個魔法已經完成了。
public class CheckableLayout extends RelativeLayout implements Checkable
{
private RadioButton _checkbox;
public CheckableLayout(Context context, AttributeSet attrs)
{
super(context, attrs);
}
@Override
protected void onFinishInflate()
{
super.onFinishInflate();
// find checkable view
int childCount = getChildCount();
for (int i = 0; i < childCount; ++i)
{
View v = getChildAt(i);
if (v instanceof RadioButton)
{
_checkbox = (RadioButton) v;
}
}
}
public boolean isChecked()
{
return _checkbox != null ? _checkbox.isChecked() : false;
}
public void setChecked(boolean checked)
{
if (_checkbox != null)
{
_checkbox.setChecked(checked);
}
}
public void toggle()
{
if (_checkbox != null)
{
_checkbox.toggle();
}
}
}
你可以用複選框或任何你需要的。
不錯。如果您使用[CompoundButton](http://developer.android.com/reference/android/widget/CompoundButton.html)而不是RadioButton,則它將像複選框或切換按鈕一樣工作。 – dgmltn 2011-04-05 17:39:02