前不久做的一个项目用到了好多自定义的view,先写个博客记录一下其中两个,比较简单,就放到一个博客里写吧。
1,分类Tab菜单条
首先自定义属性:
<declare-styleable name="titleBar">
<attr name="first" format="string|reference"></attr>
<attr name="second" format="string|reference"></attr>
<attr name="third" format="string|reference"></attr>
<attr name="forth" format="string|reference"></attr>
</declare-styleable>
上代码:自定义TabarView
public class TabBarView extends RelativeLayout implements OnClickListener {
private Context mContext;
private TextView tab1;
private TextView tab2;
private TextView tab3;
private TextView tab4;
//tab的索引
public static final int CLICK_POSITION_FIRST = 0;
public static final int CLICK_POSITION_SECOND = 1;
public static final int CLICK_POSITION_THIRD = 2;
public static final int CLICK_POSITION_FORTH = 3;
private TabClickListener onTabClickListener;
public TabBarView(Context context) {
super(context);
mContext = context;
initView();
}
public TabBarView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
initView();
TypedArray array = context.obtainStyledAttributes(attrs,
R.styleable.titleBar);
tab1.setText(array.getText(R.styleable.titleBar_first));
tab2.setText(array.getText(R.styleable.titleBar_second));
tab3.setText(array.getText(R.styleable.titleBar_third));
tab4.setText(array.getText(R.styleable.titleBar_forth));
array.recycle();
}
private void initView() {
LayoutInflater.from(mContext).inflate(R.layout.title_bar_layout, this);
tab1 = (TextView) findViewById(R.id.tv_tab1);
tab2 = (TextView) findViewById(R.id.tv_tab2);
tab3 = (TextView) findViewById(R.id.tv_tab3);
tab4 = (TextView) findViewById(R.id.tv_tab4);
tab1.setOnClickListener(this);
tab2.setOnClickListener(this);
tab3.setOnClickListener(this);
tab4.setOnClickListener(this);
}
//设置点击的tab
public void setClickPosition(int position) {
if (position == CLICK_POSITION_FIRST) {
tab1.performClick();
}
if (position == CLICK_POSITION_SECOND) {
tab2.performClick();
}
if (position == CLICK_POSITION_THIRD) {
tab3.performClick();
}
if (position == CLICK_POSITION_FORTH) {
tab4.performClick();
}
}
@Override
public void onClick(View v) {
v.setEnabled(false);
switch (v.getId()) {
case R.id.tv_tab1:
tab2.setEnabled(true);
tab3.setEnabled(true);
tab4.setEnabled(true);
if (onTabClickListener != null)
onTabClickListener.onFirstTabClick(v);
break;
case R.id.tv_tab2:
tab1.setEnabled(true);
tab3.setEnabled(true);
tab4.setEnabled(true);
if (onTabClickListener != null)
onTabClickListener.onSecondTabClick(v);
break;
case R.id.tv_tab3:
tab1.setEnabled(true);
tab2.se