安卓自定义一个 单选框
时间: 2024-03-01 20:52:39 浏览: 25
要自定义一个单选框,可以继承自 Android 的 View 类,并实现一些必要的方法。下面是一个简单的例子:
```java
public class MyRadioButton extends View {
private boolean isChecked = false;
private Paint paint = new Paint();
public MyRadioButton(Context context) {
super(context);
init();
}
public MyRadioButton(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyRadioButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
// 设置画笔的颜色和样式
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 设置 view 的大小,这里设置为 50x50
setMeasuredDimension(50, 50);
}
@Override
protected void onDraw(Canvas canvas) {
// 画一个圆形
canvas.drawCircle(getWidth() / 2, getHeight() / 2, getWidth() / 2 - 5, paint);
// 如果被选中,画一个小圆点
if (isChecked) {
canvas.drawCircle(getWidth() / 2, getHeight() / 2, getWidth() / 4, paint);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// 监听点击事件,如果被点击,就改变选中状态
if (event.getAction() == MotionEvent.ACTION_DOWN) {
isChecked = !isChecked;
invalidate();
}
return super.onTouchEvent(event);
}
}
```
这个自定义单选框只是一个简单的例子,可以根据需要添加更多的功能。要使用这个自定义单选框,只需要在布局文件中添加一个 MyRadioButton 即可:
```xml
<com.example.myapplication.MyRadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
```