我正在尝试创建自定义集中按钮。除了按钮始终与左侧对齐外,一切正常。如何使单选按钮居中?
注意:我在C#中使用Xamarin Android进行此操作。
我现在拥有的东西以及我想要实现的目标。
这是边框的AXML
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@android:color/transparent" />
<stroke android:width="1dp" android:color="@color/lightGreenColor" />
<padding android:left="5dp" android:top="5dp" android:right="5dp" android:bottom="5dp" />
</shape>
这是我的代码:
List<Telco> telcoList = new GeneralUtilities().getTelcosByCountry(getApp().selectedCountry.country_code);
RadioGroup.LayoutParams lps;
int counter = 0;
foreach(var telcoItem in telcoList)
{
counter++;
Drawable bitt = null;
RadioButton rb = new RadioButton(this);
rb.Id = counter;
rb.SetButtonDrawable(null);
IObservable<IBitmap> x = new GeneralUtilities().returnImage(telcoItem.country_img,48,48);
x.Subscribe(new Action<Splat.IBitmap>(pic => {
bitt = BitmapMixins.ToNative(pic);
Drawable normalDrawable = bitt;
Drawable focusedDrawable = bitt;
StateListDrawable stateListDrawable = new StateListDrawable();
stateListDrawable.AddState(new int[] { Android.Resource.Attribute.StateChecked, -Android.Resource.Attribute.StatePressed }, focusedDrawable);
stateListDrawable.AddState(new int[] { -Android.Resource.Attribute.StateChecked, -Android.Resource.Attribute.StatePressed }, normalDrawable);
stateListDrawable.AddState(new int[] { Android.Resource.Attribute.StateChecked, Android.Resource.Attribute.StatePressed }, focusedDrawable);
stateListDrawable.AddState(new int[] { -Android.Resource.Attribute.StateChecked, Android.Resource.Attribute.StatePressed }, normalDrawable);
rb.SetButtonDrawable(stateListDrawable);
}), ex => Console.WriteLine("Na " + ex));
StateListDrawable state = new StateListDrawable();
state.AddState(new int[] { Android.Resource.Attribute.StateChecked, -Android.Resource.Attribute.StatePressed }, Resources.GetDrawable(Resource.Drawable.item_border));
state.AddState(new int[] { -Android.Resource.Attribute.StateChecked, -Android.Resource.Attribute.StatePressed }, Resources.GetDrawable(Android.Resource.Color.Transparent));
state.AddState(new int[] { Android.Resource.Attribute.StateChecked, Android.Resource.Attribute.StatePressed }, Resources.GetDrawable(Resource.Drawable.item_border));
state.AddState(new int[] { -Android.Resource.Attribute.StateChecked, Android.Resource.Attribute.StatePressed }, Resources.GetDrawable(Android.Resource.Color.Transparent));
rb.SetBackgroundDrawable(state);
lps = new RadioGroup.LayoutParams(0, RadioGroup.LayoutParams.WrapContent);
lps.Weight = 1;
lps.Gravity = GravityFlags.Center;
lps.SetMargins(10, 10, 10, 10);
rb.Gravity = GravityFlags.Center;
telcoRadioGroup.AddView(rb, lps);
}