虽然说google自己有actionbar,还有toolbar。但是绝大部分的时候我们还是需要自定义统一样式的TitleBar。那么让我们一起来探索怎么定义一个万能的TitleBar吧!
(1)我们先把TitleBar 分为三个部分,左边,中间,右边(右边也许有2个按钮)。
并且右边和左边有可能是字,也有可能是图片
(2)那么我们就可以定义一下几个属性
1. 是否需要显示左边
2. 是否需要显示右边的
3. 如果显示左边的,并且定义了文字属性的话,那么左边的就是Textiview;如果没有定义text属性,那么就是ImageView。右边也同理
(3)
那么我们就来获取属性:
private void init(Context context, AttributeSet attrs) {
if (attrs != null) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.TitleBar);
nTitleText = a.getString(R.styleable.TitleBar_title_text);
nRightBtnText1 = a.getString(R.styleable.TitleBar_title_btn_right_text);
nRightBtnText2 = a.getString(R.styleable.TitleBar_title_btn_right_text_2);
bShowLeftBtn = a.getBoolean(R.styleable.TitleBar_title_show_left_btn, true);
nLeftBtnText = a.getString(R.styleable.TitleBar_title_btn_left_text);
bShowRightBtn1 = a.getBoolean(R.styleable.TitleBar_title_show_right_btn, false);
bShowRightBtn2 = a.getBoolean(R.styleable.TitleBar_title_show_right_btn_2, false);
nRightBtnIcon1 = a.getResourceId(R.styleable.TitleBar_title_btn_right_icon, DEFAULT_RES_ID);
nRightBtnIcon2 = a.getResourceId(R.styleable.TitleBar_title_btn_right_icon_2, DEFAULT_RES_ID);
nRightBtnTextAppearance1 = a.getResourceId(R.styleable.TitleBar_title_btn_right_text_appearance, DEFAULT_RES_ID);
nRightBtnTextAppearance2 = a.getResourceId(R.styleable.TitleBar_title_btn_right_text_appearance_2, DEFAULT_RES_ID);
a.recycle();
}
//首先根据bShowLeftBtn 来看是否要添加左边的按钮,
if (bShowLeftBtn) {
//同时如果属性里有文字,则添加的是TextView,反之则是ImageView
if (!TextUtils.isEmpty(nLeftBtnText)) {
mLeftBtn = addLeftButtonText();
} else {
mLeftBtn = addLeftImageButton();
}
}
那么我们在addLeftButtonText方法里
private View addLeftButtonText() {
//新建一个textView,并设置相关属性
TextView leftTextBtn = new TextView(context);
mLeftBtn = leftTextBtn;
leftTextBtn.setText(nLeftBtnText);
leftTextBtn.setBackgroundResource(R.drawable.bg_comm_item_selector);
leftTextBtn.setTextAppearance(context, R.style.text_17_fd618c);
leftTextBtn.setId(ViewUtil.generateViewId());
leftTextBtn.setOnClickListener(this);
leftTextBtn.setGravity(Gravity.CENTER);
leftTextBtn.setPadding(DeviceUtil.getPixelFromDip(context.getResources().getDisplayMetrics(), 13), 0,
DeviceUtil.getPixelFromDip(context.getResources().getDisplayMetrics(), 13), 0);
//设置textview应该位于的位置
LayoutParams layoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
leftTextBtn.setLayoutParams(layoutParams);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, RelativeLayout.TRUE);
layoutParams.addRule(RelativeLayout.CENTER_VERTICAL, RelativeLayout.TRUE);
//把它添加到titile里
addView(leftTextBtn);
return leftTextBtn;
}
那么标题栏和右边的menu栏,也都可以这样