虽说android有toolbar,actionbar,但现在app基本都做一套效果图,照ios来,所以都有个和ios一样有个标题栏,左边返回键,中间标题,右边也有个图标或文字,多个界面都有写布局太麻烦,也不好统一修改。于是自定义个标题栏直接放个控件,设置左边图片,标题,右边图片就行了。
效果图
xml
<com.rsd.library.widget.RTopBar
android:layout_width="match_parent"
app:leftImg="@drawable/icon_back"
app:centerText="标题"
app:rightText="保存"
android:layout_height="wrap_content"/>
其实就是先写个布局文件,继承viewgroup设置其各个属性
用到自定义属性,在attrs里声明一个declare-styleable
<declare-styleable name="RTopBar">
<attr name="leftImg" format="reference" />
<attr name="centerText" format="string" />
<attr name="rightImg" format="reference" />
<attr name="rightText" format="string" />
</declare-styleable>
里面添加想用到的属性 format为属性类别有资源,颜色,尺寸,文本等
在view初始化获取这些值
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.RTopBar, defStyleAttr, 0);
int leftId = array.getResourceId(R.styleable.RTopBar_leftImg, 0);
int rightId = array.getResourceId(R.styleable.RTopBar_rightImg, 0);
String title = array.getString(R.styleable.RTopBar_centerText);
String right = array.getString(R.styleable.RTopBar_rightText);
定义布局内容
private void init(Context context) {
this.context = context;
View view = LayoutInflater.from(context).inflate(R.layout.view_topbar, this);
leftImg = (ImageView) view.findViewById(R.id.topBar_leftImg);
centerText = (TextView) view.findViewById(R.id.topBar_title);
rightImg = (ImageView) view.findViewById(R.id.topBar_rightImg);
rightText = (TextView) view.findViewById(R.id.topBar_rightText);
leftImg.setOnClickListener(this);
rightText.setOnClickListener(this);
rightImg.setOnClickListener(this);
}
inflater获取布局,第二个参数表示布局绑定的父容器,这里是当前view
然后就是点击方法了
public void setTitleText(String title) {
centerText.setText(title);
}
public interface OnTitleClickListener {
boolean onClick(boolean isRight);//参数表示点击的左边还是右边。
}
//左边的点击事件,左边一般都是返回,也有例外,返回true就处理点击事件不用返回了
if (onTitleClickListener != null && onTitleClickListener.onClick(false)) {
return;
} else {
((Activity) context).finish();
}