前言
系统自带的Tablayout用的也不错但是有些功能还不能满足我们这边开发,所以我这边自定义了一个tablayout提供了自定义tab线的长度以及,移动速度,以及禁止某个滑动(tablayout基本功能也提供了)
效果图
QQ20170327-165412-HD(1).gif
实现步骤
- 构造方法添加子控件
添加一些xml定义的属性
public MyIndicator(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.setGravity(Gravity.CENTER_VERTICAL);
this.setLayoutParams(new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.Indicator, 0, 0);
mColor = array.getColor(R.styleable.Indicator_indicatorColor, Color.RED);
mList = getContext().getResources().getStringArray(array.getResourceId(R.styleable.Indicator_array, 0));
mTextNomal = array.getInteger(R.styleable.Indicator_text_nomal_size, 12);
mTextPress = array.getInteger(R.styleable.Indicator_text_press_size, 13);
mText_Nomal = array.getColor(R.styleable.Indicator_text_nomal_color, Color.GRAY);
mText_Press = array.getColor(R.styleable.Indicator_text_press_color, Color.BLACK);
mSelected = array.getInteger(R.styleable.Indicator_selected, 0);
isFull = array.getBoolean(R.styleable.Indicator_isFull, false);
mAnimationTime = array.getInteger(R.styleable.Indicator_speed, 300);
mBai = array.getFloat(R.styleable.Indicator_multiply, (float) 1.2);
mHeight = array.getInteger(R.styleable.Indicator_line_hegith, 5);
for (int i = 0; i < mList.length; i++) {
mListTitle.add(mList[i]);
}
array.recycle();
}
- onLayout初始化布局
添加控件
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
if (!mIsCheck) {
mIsCheck = true;
initView();
}
}
添加textview以及线
/**
* 初始化布局
*/
private void initView() {
measure(0, 0);
//获取每个textview布局所占的宽度
mContWidth = getWidth() / mListTitle.size();
//添加线
mLine = new View(getContext());
addView(mLine);
int mWeight;
if (isFull) {
mWeight = mContWidth;
} else {
mWeight = (int) (setLineLength(mListTitle.get(mSelected)) * mBai);
if (mWeight > mContWidth) {
mWeight = mContWidth;
}
}
//设置线的基本属性
LayoutParams mLayoutParams1 = new LayoutParams(mWeight, mHeight);
mLayoutParams1.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
mLine.setLayoutParams(mLayoutParams1);
mLine.setBackgroundColor(mColor);
//获取上一次所在位置
mEndAddress = mContWidth * mSelected + (mContWidth - mWeight) / 2;
//添加textview
for (int i = 0; i < mListTitle.size(); i++) {
addTextView(i);
}
//初始化点击事件
setListener();
}
/**
* 添加textview
*/
private void addTextView(int i)