直接上效果圖片
圖片效果1
圖片效果二
實現(xiàn)思路
通過自定義view 繼承至RadioGroup,通過RadioGroup的監(jiān)聽事件个少,來達到選項切換的效果。
setOrientation(LinearLayout.HORIZONTAL); //設(shè)置橫向排列
line.setBounds(0, 0, 1, line.getMinimumHeight()); //設(shè)置分割線
if (null != attrs) {
TypedArray typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.SegmentView);
//設(shè)置選項的個數(shù)
number = typedArray.getInt(R.styleable.SegmentView_sv_number, DEFAULT_NUM);
//文字的大小
textSize = typedArray.getInt(R.styleable.SegmentView_text_size, 16);
initTextView(number);
typedArray.recycle();
}
//注冊監(jiān)聽事件
setOnCheckedChangeListener(this);
初始化視圖
private void initTextView(int number) {
if (number <= 0)
return;
setBackgroundResource(R.drawable.shape_guide_corner20_gray);
radioButtons = new RadioButton[number];
titles = new String[number];
//不同狀態(tài)下的按鈕顯示不同的顏色
ColorStateList csl = getResources().getColorStateList(R.color.selector_segment_color_tab);
RadioButton radioButton;
//實現(xiàn)中間部分的textview潭辈,兩邊都是圓角
for (int i = 0; i < number; i++) {
radioButton = new RadioButton(mContext);
radioButton.setId(START_ID + i);
// 設(shè)置textview的布局寬高并設(shè)置為weight屬性都為1
radioButton.setLayoutParams(new LayoutParams(dip2px(mContext, 90),
LayoutParams.MATCH_PARENT, 1));
radioButton.setBackgroundResource(R.drawable.selector_tv_corner20_guid);
radioButton.setCompoundDrawables(null, null, line, null);
radioButton.setTextColor(csl);
radioButton.setText(titles[i]);
radioButton.setGravity(Gravity.CENTER);
radioButton.setPadding(0, 12, 0, 12);
radioButton.setButtonDrawable(null);
setSegmentTextSize(radioButton, textSize);
radioButtons[i] = radioButton;
}
//處理最后一個radiobutton线罕,去掉右邊的線
radioButtons[number - 1].setCompoundDrawables(null, null, null, null);
// 加入textview
this.removeAllViews();
for (RadioButton rb : radioButtons) {
this.addView(rb);
}
this.invalidate();//重新draw()
//有時候會出現(xiàn)點擊了一次,再點擊其他的時候總是會出現(xiàn)兩個
if (number > 1) {
radioButtons[1].setChecked(true);
}
radioButtons[0].setChecked(true);
}
在監(jiān)聽事件中般哼,每一次切狀態(tài)的時候吴汪,將所有的按鈕都恢復(fù)為未選中的狀態(tài)
@Override
public void onCheckedChanged(RadioGroup radioGroup, int checkId) {
int index = checkId - START_ID; //當(dāng)前選中的按鈕序號
if (null == radioButtons || number <= index)
return;
for (RadioButton button : radioButtons) { //恢復(fù)為默認的狀態(tài)
button.setCompoundDrawables(null, null, line, null);
}
if (index > 0) {
radioButtons[index - 1].setCompoundDrawables(null, null, null, null);
}
radioButtons[index].setCompoundDrawables(null, null, null, null);
lastCheckIndex = index;
//最后一個需要將右邊的分割線去掉
radioButtons[number - 1].setCompoundDrawables(null, null, null, null);
if (null != segmentListener) { //處理自定義接口事件
segmentListener.onSegmentViewClick(this, index);
}
}
在按鈕選項狀態(tài)發(fā)生變化的時候,觸發(fā)自定義的一個接口
// 定義一個接口接收點擊事件
public interface onSegmentViewClickListener {
public void onSegmentViewClick(View view, int postion);
}
public void setOnSegmentViewClickListener(onSegmentViewClickListener segmentListener) {
this.segmentListener = segmentListener;
}
最后附上完整的代碼鏈接完整項目demo