1
我正在創建如下定義的自定義RadioGroup。當RadioButton以編程方式添加時,Android RadioGroup的行爲會有所不同
MyRadioGroup.cpp
public class MyRadioGroup
extends RadioGroup
{
...
public MyRadioGroup(Context context, AttributeSet attrs)
{
super(context, attrs);
mContext = context;
init(attrs);
}
private void init(AttributeSet attrs)
{
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.my_radio_group, this);
}
public String getSelection()
{
View radioButton = findViewById(getCheckedRadioButtonId());
return radioButton.getTag().toString();
}
}
my_radio_group.xml有定義爲如下幾個按鈕...
<merge
xmlns:android="http://schemas.android.com/apk/res/android">
<RadioButton
android:id="@+id/rbOne"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:background="@drawable/rb_selection_background"
android:button="@null"
android:gravity="center_horizontal"
android:tag="One"
android:text="Radio Button 1"
android:textColor="@color/rptText"
android:textSize="18sp"/>
...
</merge>
rb_selection_background.xml繪製
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@drawable/simple_border"
android:state_checked="true"/>
</selector>
使用此設置,我可以得到我想要的無循環按鈕的結果,並且選定的按鈕在文本週圍顯示一個簡單的邊框。
然後我做了一個改變,從字符串數組資源動態生成我的單選按鈕。像這樣...總是顯示在最後一個單選按鈕
private void init(AttributeSet attrs)
{
Drawable selectionBg = ResourcesCompat.getDrawable(getResources(),
R.drawable.rb_selection_background,
null);
String[] rbStrings = getResources().getStringArray(R.array.rb_strings);
for(int i = 0; i < rbStrings.length; ++i)
{
RadioButton rb = new RadioButton(mContext);
LayoutParams lp = new LayoutParams(0, LayoutParams.WRAP_CONTENT);
lp.weight = 1;
rb.setText(rbStrings[i]);
rb.setTag(rbStrings[i]);
rb.setTextSize(18);
rb.setGravity(Gravity.CENTER_HORIZONTAL);
rb.setButtonDrawable(0);
rb.setBackground(selectionBg);
addView(rb, lp);
}
}
現在不管我點擊了簡單的邊界,單選按鈕。無線電組的狀態是正確的,因爲當我調用getSelection()時,它確實返回所選單選按鈕的標籤。
回到我的問題,爲什麼行爲不同?有沒有一種方法可以通過編程方式添加單選按鈕時獲得所需的行爲?謝謝。