直接上效果图片
实现思路
通过自定义view 继承至RadioGroup,通过RadioGroup的监听事件,来达到选项切换的效果。
setOrientation(LinearLayout.HORIZONTAL); //设置横向排列
line.setBounds(0, 0, 1, line.getMinimumHeight()); //设置分割线
if (null != attrs) {
TypedArray typedArray = mContext.obtainStyledAttributes(attrs, R.styleable.SegmentView);
//设置选项的个数
number = typedArray.getInt(R.styleable.SegmentView_sv_number, DEFAULT_NUM);
//文字的大小
textSize = typedArray.getInt(R.styleable.SegmentView_text_size, 16);
initTextView(number);
typedArray.recycle();
}
//注册监听事件
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];
//不同状态下的按钮显示不同的颜色
ColorStateList csl = getResources().getColorStateList(R.color.selector_segment_color_tab);
RadioButton radioButton;
//实现中间部分的textview,两边都是圆角
for (int i = 0; i < number; i++) {
radioButton = new RadioButton(mContext);
radioButton.setId(START_ID + i);
// 设置textview的布局宽高并设置为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()
//有时候会出现点击了一次,再点击其他的时候总是会出现两个
if (number > 1) {
radioButtons[1].setChecked(true);
}
radioButtons[0].setChecked(true);
}
在监听事件中,每一次切状态的时候,将所有的按钮都恢复为未选中的状态
@Override
public void onCheckedChanged(RadioGroup radioGroup, int checkId) {
int index = checkId - START_ID; //当前选中的按钮序号
if (null == radioButtons || number <= index)
return;
for (RadioButton button : radioButtons) { //恢复为默认的状态
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);
}
}
在按钮选项状态发生变化的时候,触发自定义的一个接口
// 定义一个接口接收点击事件
public interface onSegmentViewClickListener {
public void onSegmentViewClick(View view, int postion);
}
public void setOnSegmentViewClickListener(onSegmentViewClickListener segmentListener) {
this.segmentListener = segmentListener;
}
最后附上完整的代码链接完整项目demo