完整项目:Github,包括使用说明
https://github.com/CodeManLH/SegmentedControl
先上图
写项目时有个需求需要展示SegmentedControl(分段控制器),iOS是有的,可惜Android没有,本来想网上找一个用的,但是都不符合需求,项目用的是两行,网上大多数都是用RadioGroup,去实现的,这里我用自定义继承LinearLayout 实现,因为是两行没办法,那就自己动手写一个吧,实现不复杂,上代码
先说单个Segmented,定义一个类继承LinearLayout
Segmented
public class Segmented extends LinearLayout {
...
// 这里接收定义好的属性,然后给属性赋值
public Segmented(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext = context;
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SegmentedItem);
mText = a.getString(R.styleable.SegmentedItem_text);
mDescription = a.getString(R.styleable.SegmentedItem_description);
// 接收Dimension时要注意,如果在布局文件定义sp,在setTextSize时,统一把单位换成px,不然字体会很大
mTextSize = a.getDimension(R.styleable.SegmentedItem_textSize,DensityUtil.toSp(context,12));
mDescriptionSize = a.getDimension(R.styleable.SegmentedItem_descriptionSize,DensityUtil.toSp(context,12));
mTextColor = a.getColor(R.styleable.SegmentedItem_textColor,0);
mTextSelectedColor = a.getColor(R.sty