最近項目有個單選按鈕,不過比開關多一個選項,
單選按鈕,分一選一,二選一,三選一,四選一。。。。
一選一,用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