最近项目有个单选按钮,不过比开关多一个选项,
单选按钮,分一选一,二选一,三选一,四选一。。。。
一选一,用CheckBox。
单一按钮是否选中
见我另一片博:http://blog.csdn.net/shao941122/article/details/49333139
二选一,用开关按钮
其实开关按钮理解成二选一有点牵强,
这个可以理解为,开,关,两个组件分别是否被选中。
多选一,分段式RadioGroup
步入正题,先看效果,后看代码
有些大神已经看出来了,这个改写的GitHub上的项目。
传送门:https://github.com/vinc3m1/android-segmentedradiobutton
Demo下载地址:http://download.csdn.net/detail/shao941122/9363521
在此我改写了一下,然后分析下源码
简单两个类:
package com.makeramen.segmented;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.RadioGroup;
/**
* 分段式 RadioGroup
*
* @author shaoshuai
*
*/
public class SegmentedRadioGroup extends RadioGroup {
public SegmentedRadioGroup(Context context) {
super(context);
}
public SegmentedRadioGroup(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
changeButtonsImages();
}
private void changeButtonsImages() {
int count = super.getChildCount();
if (count > ) {
super.getChildAt().setBackgroundResource(com.makeramen.segmented.R.drawable.segment_radio_left);
for (int i = ; i < count - ; i++) {
super.getChildAt(i).setBackgroundResource(com.makeramen.segmented.R.drawable.segment_radio_middle);
}
super.getChildAt(count - ).setBackgroundResource(com.makeramen.segmented.R.drawable.segment_radio_right);
} else if (count == ) {// 只有一个,选中了就不能后悔
super.getChildAt().setBackgroundResource(com.makeramen.segmented.R.drawable.segment_radio_middle);
}
}
}
还有一个
package com.makeramen.segmented;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.RadioButton;
/**
* 图片居中的 RadioButton
*
* @author shaoshuai
*
*/
public class CenteredRadioImageButton extends RadioButton {
Drawable image;
public CenteredRadioImageButton(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, com.makeramen.segmented.R.styleable.CompoundButton, , );
image = a.getDrawable();
setButtonDrawable(android.R.color.transparent);
a.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (image != null) {
image.setState(getDrawableState());
// 缩放图像以适应里面的按钮
int imgHeight = image.getIntrinsicHeight();
int imgWidth = image.getIntrinsicWidth();
int btnWidth = getWidth();
int btnHeight = getHeight();
float scale;
if (imgWidth <= btnWidth && imgHeight <= btnHeight) {
scale = f;
} else {
scale = Math.min((float) btnWidth / (float) imgWidth, (float) btnHeight / (float) imgHeight);
}
int dx = (int) ((btnWidth - imgWidth * scale) * f + f);
int dy = (int) ((btnHeight - imgHeight * scale) * f + f);
image.setBounds(dx, dy, (int) (dx + imgWidth * scale), (int) (dy + imgHeight * scale));
image.draw(canvas);
}
}
}
Demo下载地址:http://download.csdn.net/detail/shao941122/9363521