viewui自定义Radio 单选框为图片
时间: 2023-05-26 08:01:29 浏览: 51
A:您可以使用ViewGroup配合ImageView和TextView来自定义一个带有图片的单选框:
1. 新建一个布局文件 custom_radio.xml,定义一个LinearLayout作为容器,内嵌一个ImageView和TextView,分别用来显示选中和未选中状态的图片和文字:
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="@+id/radio_btn"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_marginRight="8dp"
android:src="@drawable/radio_unchecked"/>
<TextView
android:id="@+id/radio_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="RadioButton"/>
</LinearLayout>
```
2. 在Java代码中创建一个自定义RadioGroup,并且遍历所有的custom_radio子View,设置点击事件和状态:
```
public class CustomRadioGroup extends LinearLayout implements View.OnClickListener {
private int mCheckedId = -1;
public CustomRadioGroup(Context context) {
this(context, null);
}
public CustomRadioGroup(Context context, AttributeSet attrs) {
super(context, attrs);
setOrientation(VERTICAL);
}
@Override
public void onClick(View v) {
if (mCheckedId != v.getId()) {
setCheckedState(v.getId());
mCheckedId = v.getId();
}
}
public int getCheckedId() {
return mCheckedId;
}
public void setCheckedId(int id) {
if (mCheckedId != id) {
mCheckedId = id;
setCheckedState(mCheckedId);
}
}
private void setCheckedState(int id) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
if (child instanceof ViewGroup) {
ViewGroup group = (ViewGroup) child;
ImageView btn = group.findViewById(R.id.radio_btn);
if (group.getId() == id) {
btn.setImageResource(R.drawable.radio_checked);
} else {
btn.setImageResource(R.drawable.radio_unchecked);
}
}
}
}
public void addRadio(View view) {
view.setId(View.generateViewId());
view.setOnClickListener(this);
addView(view);
}
}
```
3. 在 Activity 中使用自定义RadioGroup,并添加custom_radio子View:
```
CustomRadioGroup radioGroup = findViewById(R.id.custom_radio_group);
LayoutInflater inflater = LayoutInflater.from(this);
View view1 = inflater.inflate(R.layout.custom_radio, null);
TextView textView1 = view1.findViewById(R.id.radio_text);
textView1.setText("Radio1");
View view2 = inflater.inflate(R.layout.custom_radio, null);
TextView textView2 = view2.findViewById(R.id.radio_text);
textView2.setText("Radio2");
radioGroup.addRadio(view1);
radioGroup.addRadio(view2);
```
这样就完成了一个自定义的带有图片的单选框。