我正在尝试创建一种比例视图。因此,我使用单选按钮,文本位于单选按钮的顶部。
在我的布局文件中定义它很好:
<LinearLayout
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RadioButton
android:layout_height="match_parent"
android:layout_width="match_parent"
android:text="Text on top"
android:button="@null"
android:drawableBottom="@android:drawable/btn_radio"
android:gravity="center"
android:layout_weight="1"/>
<RadioButton
android:layout_height="match_parent"
android:layout_width="match_parent"
android:text="Text on top"
android:button="@null"
android:drawableBottom="@android:drawable/btn_radio"
android:gravity="center"
android:layout_weight="1"/>
</RadioGroup>
</LinearLayout>
结果如下:
现在我只需要
单选
单选按钮
以编程方式
并将它们添加到放射组。
我试过这个代码,但它不起作用:
RadioButton rb = new RadioButton(Context);
LinearLayout.LayoutParams rbParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
rb.SetButtonDrawable(null);
rb.SetCompoundDrawablesWithIntrinsicBounds(null,null,null, Resources.GetDrawable(Android.Resource.Drawable.ButtonRadio));
rb.Text = "Test";
rb.Gravity = GravityFlags.Center;
rbParams.Weight = 1;
rb.LayoutParameters = rbParams;
radioGroup.AddView(rb);
我想
SetButtonDrawable
和/或
SetCompoundDrawable
与
android:button
android:drawableBottom
只使用代码,而不在
.axml
文件,我刚收到短信”
编辑2:
使用SetCompoundDrawablesWithIntrinsicBounds,我看到单选按钮,但文本没有居中。
编辑3:
好的,有了迈克的评论(在代码中编辑),它正确地显示了一个单选按钮
接下来的问题是:
因为我需要添加多个单选按钮,所以我尝试了一个简单的循环,上面的代码相同。
for (int i = 0; i < 4; i++)
{
RadioButton rb = new RadioButton(Context);
...
radioGroup.AddView(rb);
}
问题是,它仍然只显示一个单选按钮。唯一发生的事情是,单选按钮和文本之间出现了一点空间。
编辑4:
与
LayoutParams.WrapContent
我可以显示所有单选按钮。但我的意图是,单选按钮填满了放射组。所以我用
match_parent
weight=1
每个单选按钮将得到相同的空间。
编辑5:
什么有效:
在for循环中创建单选按钮后,我调用以下代码:
var count = radioGroup.ChildCount;
for (int i = 0; i < count; i++)
{
var currentRb = radioGroup.GetChildAt(i);
LinearLayout.LayoutParams rbParams2 = new LinearLayout.LayoutParams(0,
ViewGroup.LayoutParams.WrapContent);
rbParams2.Weight = 1;
currentRb.LayoutParameters = rbParams2;
}
但是谢谢你
Mike
一步一步找到这个解决方案!