纯手工打造一个通用的标题栏TitleBar

Github传送地址,欢迎Star,Pull及issue

首先看一个项目已经有标题栏

这个自定义组合控件的写法是使用布局填充器(LayoutInflater)初始化XML布局

但是有没有想过这样一个问题,LayoutInflater需要通过XML解析再使用代码初始化View的,如果我们直接使用代码初始化View呢?效率和性能是不是更好了?显而易见当然就是了。

  • 整容前(TitleActionBar)
  • 整容后(TitleBar)

有细心的同学就会发现了第一张图中的状态栏颜色和Title的颜色明显不搭,这是因为我们使用了沉浸式状态,而这个TitleActionBar对沉浸式状态不是很友好,第二张图就显得比较友好了,接下来让我们用纯手工编写一个通用的TitleBar吧

TitleBar布局解析

/**
 * 标题栏
 */
public class TitleBar extends FrameLayout {

    public TitleBar(Context context) {
        this(context, null, 0);
    }

    public TitleBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TitleBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
}

创建一个Builder

使用这个Builder构建一个LinearLayout,然后往LinearLayout添加三个TextView,最后将这个LinearLayout添加到TitleBar中

static class Builder {

    private LinearLayout mMainLayout;
    private TextView mLeftView;
    private TextView mTitleView;
    private TextView mRightView;

    private View mLineView;

    Builder(Context context) {
        mMainLayout = new LinearLayout(context);
        mMainLayout.setOrientation(LinearLayout.HORIZONTAL);
        mMainLayout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        mLeftView = new TextView(context);
        mLeftView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
        mLeftView.setPadding(Builder.dp2px(context, 15), 0, Builder.dp2px(context, 15), 0);
        mLeftView.setCompoundDrawablePadding(Builder.dp2px(context, 5));
        mLeftView.setGravity(Gravity.CENTER_VERTICAL);
        mLeftView.setSingleLine();
        mLeftView.setEllipsize(TextUtils.TruncateAt.END);
        mLeftView.setEnabled(false);

        mTitleView = new TextView(context);
        LinearLayout.LayoutParams titleParams = new LinearLayout.LayoutParams(1, ViewGroup.LayoutParams.MATCH_PARENT);
        titleParams.weight = 1;
        titleParams.leftMargin = Builder.dp2px(context, 10);
        titleParams.rightMargin = Builder.dp2px(context, 10);
        mTitleView.setLayoutParams(titleParams);
        mTitleView.setGravity(Gravity.CENTER);
        mTitleView.setSingleLine();
        mTitleView.setEllipsize(TextUtils.TruncateAt.END);
        mTitleView.setEnabled(false);

        mRightView = new TextView(context);
        mRightView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
        mRightView.setPadding(Builder.dp2px(context, 15), 0, Builder.dp2px(context, 15), 0);
        mRightView.setCompoundDrawablePadding(Builder.dp2px(context, 5));
        mRightView.setGravity(Gravity.CENTER_VERTICAL);
        mRightView.setSingleLine();
        mRightView.setEllipsize(TextUtils.TruncateAt.END);
        mRightView.setEnabled(false);

        mLineView = new View(context);
        FrameLayout.LayoutParams lineParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1);
        lineParams.gravity = Gravity.BOTTOM;
        mLineView.setLayoutParams(lineParams);
    }

    LinearLayout getMainLayout() {
        return mMainLayout;
    }

    View getLineView() {
        return mLineView;
    }

    TextView getLeftView() {
        return mLeftView;
    }

    TextView getTitleView() {
        return mTitleView;
    }

    TextView getRightView() {
        return mRightView;
    }

    /**
     * 获取ActionBar的高度
     */
    static int getActionBarHeight(Context context) {
        TypedArray ta = context.obtainStyledAttributes(new int[]{android.R.attr.actionBarSize});
        int actionBarSize = (int) ta.getDimension(0, 0);
        ta.recycle();
        return actionBarSize;
    }

    /**
     * dp转px
     */
    static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * sp转px
     */
    static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }
}

初始化View

private LinearLayout mMainLayout;
private TextView mLeftView;
private TextView mTitleView;
private TextView mRightView;

private View mLineView;

private void initView(Context context) {
    Builder builder = new Builder(context);
    mMainLayout = builder.getMainLayout();
    mLineView = builder.getLineView();
    mTitleView = builder.getTitleView();
    mLeftView = builder.getLeftView();
    mRightView = builder.getRightView();

    mMainLayout.addView(mLeftView);
    mMainLayout.addView(mTitleView);
    mMainLayout.addView(mRightView);

    addView(mMainLayout, 0);
    addView(mLineView, 1);
}

定义一些属性值

<declare-styleable name="TitleBar">
    <!-- 标题 -->
    <attr name="title" format="string" />
    <attr name="title_left" format="string"/>
    <attr name="title_right" format="string" />
    <!-- 图标 -->
    <attr name="icon_left" format="reference" />
    <attr name="icon_right" format="reference" />
    <!-- 返回按钮,默认开 -->
    <attr name="icon_back" format="boolean" />
    <!-- 文字颜色 -->
    <attr name="color_title" format="color" />
    <attr name="color_right" format="color" />
    <attr name="color_left" format="color" />
    <!-- 文字大小 -->
    <attr name="size_title" format="dimension" />
    <attr name="size_right" format="dimension" />
    <attr name="size_left" format="dimension" />
    <!-- 按钮背景 -->
    <attr name="background_left" format="reference|color" />
    <attr name="background_right" format="reference|color" />
    <!-- 分割线 -->
    <attr name="line" format="boolean" />
    <attr name="color_line" format="color" />
</declare-styleable>

初始化属性样式

private void initStyle(AttributeSet attrs) {

    TypedArray ta = getContext().obtainStyledAttributes(attrs, R.styleable.TitleBar);

    //标题设置

    if (ta.hasValue(R.styleable.TitleBar_title_left)) {
        setLeftTitle(ta.getString(R.styleable.TitleBar_title_left));
    }

    if (ta.hasValue(R.styleable.TitleBar_title)) {
        setTitle(ta.getString(R.styleable.TitleBar_title));
    } else {
        //如果当前上下文对象是Activity,就获取Activity的标题
        if (getContext() instanceof Activity) {
            //获取清单文件中的label属性值
            CharSequence label = ((Activity) getContext()).getTitle();
            //如果Activity没有设置label属性,则默认会返回APP名称,需要过滤掉
            if (label != null && !label.toString().equals("")) {

                try {
                    PackageManager packageManager = getContext().getPackageManager();
                    PackageInfo packageInfo = packageManager.getPackageInfo(
                            getContext().getPackageName(), 0);

                    if (!label.toString().equals(packageInfo.applicationInfo.loadLabel(packageManager).toString())) {
                        setTitle(label);
                    }
                } catch (PackageManager.NameNotFoundException ignored) {}
            }
        }
    }

    if (ta.hasValue(R.styleable.TitleBar_title_right)) {
        setRightTitle(ta.getString(R.styleable.TitleBar_title_right));
    }

    // 图标设置

    if (ta.hasValue(R.styleable.TitleBar_icon_left)) {
        setLeftIcon(getContext().getResources().getDrawable(ta.getResourceId(R.styleable.TitleBar_icon_left, 0)));
    } else {
        // 显示返回图标
        if (ta.getBoolean(R.styleable.TitleBar_icon_back, true)) {
            setLeftIcon(getContext().getResources().getDrawable(R.mipmap.ico_back_black));
        }
    }

    if (ta.hasValue(R.styleable.TitleBar_icon_right)) {
        setRightIcon(getContext().getResources().getDrawable(ta.getResourceId(R.styleable.TitleBar_icon_right, 0)));
    }

    //文字颜色设置
    mLeftView.setTextColor(ta.getColor(R.styleable.TitleBar_color_left, 0xFF666666));
    mTitleView.setTextColor(ta.getColor(R.styleable.TitleBar_color_title, 0xFF222222));
    mRightView.setTextColor(ta.getColor(R.styleable.TitleBar_color_right, 0xFFA4A4A4));

    //文字大小设置
    mLeftView.setTextSize(TypedValue.COMPLEX_UNIT_PX, ta.getDimensionPixelSize(R.styleable.TitleBar_size_left, Builder.sp2px(getContext(), 14)));
    mTitleView.setTextSize(TypedValue.COMPLEX_UNIT_PX, ta.getDimensionPixelSize(R.styleable.TitleBar_size_title, Builder.sp2px(getContext(), 16)));
    mRightView.setTextSize(TypedValue.COMPLEX_UNIT_PX, ta.getDimensionPixelSize(R.styleable.TitleBar_size_right, Builder.sp2px(getContext(), 14)));

    //背景设置
    mLeftView.setBackgroundResource(ta.getResourceId(R.styleable.TitleBar_background_left, R.drawable.selector_selectable_transparent));
    mRightView.setBackgroundResource(ta.getResourceId(R.styleable.TitleBar_background_right, R.drawable.selector_selectable_transparent));

    //分割线设置
    mLineView.setVisibility(ta.getBoolean(R.styleable.TitleBar_line, true) ? View.VISIBLE : View.GONE);
    mLineView.setBackgroundColor(ta.getColor(R.styleable.TitleBar_color_line, 0xFFECECEC));

    //回收TypedArray
    ta.recycle();

    //设置默认背景
    if (getBackground() == null) {
        setBackgroundColor(0xFFFFFFFF);
    }
}

public void setTitle(CharSequence text) {
    mTitleView.setText(text);
    postDelayed(this, 100);
}

public void setLeftTitle(CharSequence text) {
    mLeftView.setText(text);
    postDelayed(this, 100);
}

public void setRightTitle(CharSequence text) {
    mRightView.setText(text);
    postDelayed(this, 100);
}

public void setLeftIcon(Drawable drawable) {
    mLeftView.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null);
    postDelayed(this, 100);
}

public void setRightIcon(Drawable drawable) {
    mRightView.setCompoundDrawablesWithIntrinsicBounds(null, null, drawable, null);
    postDelayed(this, 100);
}

// Runnable

@Override
public void run() {
    //更新中间标题的内边距,避免向左或者向右偏移
    int leftSize = mLeftView.getWidth();
    int rightSize = mRightView.getWidth();
    if (leftSize != rightSize) {
        if (leftSize > rightSize) {
            mTitleView.setPadding(0, 0, leftSize - rightSize, 0);
        } else {
            mTitleView.setPadding(rightSize - leftSize, 0, 0, 0);
        }
    }

    //更新View状态
    if (!"".equals(mLeftView.getText().toString()) || mLeftView.getCompoundDrawables()[0] != null) {
        mLeftView.setEnabled(true);
    }
    if (!"".equals(mTitleView.getText().toString())) {
        mTitleView.setEnabled(true);
    }
    if (!"".equals(mRightView.getText().toString()) || mRightView.getCompoundDrawables()[2] != null) {
        mRightView.setEnabled(true);
    }
}

这个有个地方需要特别注意的是:标题栏的默认标题是来自Activity在清单文件中的label属性,为什么要那么做呢,因为系统原生的ActionBar也是那么做,这样做的好处是可以在清单文件中快速查找到需要的Activity,所以强烈建议大家那么做

定义默认TitleBar的默认高度为Action的高度值

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    //设置TitleBar默认的高度
    if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST || MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.UNSPECIFIED) {
        super.onMeasure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(Builder.getActionBarHeight(getContext()), MeasureSpec.EXACTLY));
    } else {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

处理监听事件

@Override
protected void onAttachedToWindow() {
    super.onAttachedToWindow();
    //设置监听
    mTitleView.setOnClickListener(this);
    mLeftView.setOnClickListener(this);
    mRightView.setOnClickListener(this);
}

@Override
protected void onDetachedFromWindow() {
    //移除监听
    mTitleView.setOnClickListener(null);
    mLeftView.setOnClickListener(null);
    mRightView.setOnClickListener(null);
    super.onDetachedFromWindow();
}

public void setOnTitleBarListener(OnTitleBarListener l) {
    mListener = l;
}

public interface OnTitleBarListener {

    void onLeftClick(View v);

    void onTitleClick(View v);

    void onRightClick(View v);
}

// View.OnClickListener

@Override
public void onClick(View v) {
    if (mListener == null) return;

    if (v == mLeftView) {
        mListener.onLeftClick(v);
    }else if (v == mTitleView) {
        mListener.onTitleClick(v);
    }else if (v == mRightView) {
        mListener.onRightClick(v);
    }
}

大功告成

接下来让我们对比一组数据

类名 Java行数 XML行数 Layout数 View数 支持扩展 执行效率
TitleActionBar 386 74 4 5 不支持 一般
TitleBar 311 0 2 4 支持自定义
  • 整容前(TitleActionBar)需要:Java 386行代码 + XML 74行代码
  • 整容后(TitleBar)需要:纯Java 311行代码

控件的性能和代码执行数有一定的关联,但是最重要的是不需要再通过XML去解析,同时使用LayoutInflater会多出一层多余的布局嵌套(因为LayoutInflater最终会调用ViewGroup中的addView方法,具体详情请查看源码,这里不再细说)

应用的标题栏是我们十分常用的控件,也是APP最重要的UI控件之一,标题栏的优化关乎整个APP,因为每个界面几乎都会使用到这个控件,所以更应该做好性能优化

点此下载Demo,最后记得点赞 + Star

Android 技术讨论 Q 群:10047167

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,117评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,963评论 1 290
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 107,897评论 0 240
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,805评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,208评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,535评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,797评论 2 311
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,493评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,215评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,477评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,988评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,325评论 2 252
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,971评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,055评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,807评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,544评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,455评论 2 266

推荐阅读更多精彩内容