最近項目有個單選按鈕,不過比開關多一個選項,
單選按鈕,分一選一,二選一,三選一,四選一。。。。
一選一,用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 > 1) {
super.getChildAt(0).setBackgroundResource(com.makeramen.segmented.R.drawable.segment_radio_left);
for (int i = 1; i < count - 1; i++) {
super.getChildAt(i).setBackgroundResource(com.makeramen.segmented.R.drawable.segment_radio_middle);
}
super.getChildAt(count - 1).setBackgroundResource(com.makeramen.segmented.R.drawable.segment_radio_right);
} else if (count == 1) {// 只有一個,選中了就不能後悔
super.getChildAt(0).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, 0, 0);
image = a.getDrawable(1);
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 = 1.0f;
} else {
scale = Math.min((float) btnWidth / (float) imgWidth, (float) btnHeight / (float) imgHeight);
}
int dx = (int) ((btnWidth - imgWidth * scale) * 0.5f + 0.5f);
int dy = (int) ((btnHeight - imgHeight * scale) * 0.5f + 0.5f);
image.setBounds(dx, dy, (int) (dx + imgWidth * scale), (int) (dy + imgHeight * scale));
image.draw(canvas);
}
}
}