gpt4 book ai didi

以编程方式添加 RadioButtons 时,Android RadioGroup 的行为有所不同

转载 作者:行者123 更新时间:2023-11-30 00:38:36 28 4
gpt4 key购买 nike

我正在创建一个定义如下的自定义 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() 时它确实返回了被选中的单选按钮的标签。

回到我的问题,为什么行为不同?以编程方式添加单选按钮时,有没有办法获得我想要的行为?谢谢。

最佳答案

改变

rb.setBackground(selectionBg);

rb.setBackgroundResource(R.drawable.rb_selection_background);

成功了。

我没有解释为什么,我需要进一步研究每种方法。

关于以编程方式添加 RadioButtons 时,Android RadioGroup 的行为有所不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42957830/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com