标题栏

虽说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();
                }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值