Android ActionBar高级自定义——设置标题居中和添加控件

来源:互联网 发布:spss数据差异性分析 编辑:程序博客网 时间:2024/05/28 06:06

关于ActionBar的一些常见使用方法我已经在之前两篇博文(Android ActionBar完全解析(上)和Android ActionBar完全解析(下))里面介绍的比较完全了,然而在日常使用中我们会发现一些知名厂商的APP的ActionBar多姿多彩(其实我想说的是千奇百怪),那么他们是如何做到的呢。首先我们先看一下一些典型的例子:

网易云


Fuubo


QQ



如此看来是不是和Google官方提供的参考样式不太一样呢?尤其是QQ,基本上就不是遵循Google的设计规范来做的(这样设计好不好另说,这里我们只讨论实现方法),那么它们又是如何实现的呢?

首先我们知道ActionBar可以添加自定义的布局样式(setCustomView),那么突破口就在这里了,我们可以通过自定义布局样式,在这个布局文件里面添加我们需要在ActionBar上面显示的标题和控件等。

    @Override         protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        setCustomActionBar();    }    private void setCustomActionBar() {        ActionBar.LayoutParams lp =new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER);        View mActionBarView = LayoutInflater.from(this).inflate(R.layout.actionbar_layout, null);        ActionBar actionBar = getActionBar();        actionBar.setCustomView(mActionBarView, lp);        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);        actionBar.setDisplayShowCustomEnabled(true);        actionBar.setDisplayShowHomeEnabled(false);        actionBar.setDisplayShowTitleEnabled(false);    }

res/layout/actionbar_layout.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent">    <TextView        android:id="@android:id/title"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"        android:text="标题"        android:textColor="#ffffff"/></RelativeLayout>

这样即可设置ActionBar的标题居中显示了,注意如果ActionBar上面有Action View的话,布局会向中间收缩。


和标题居中类似,我们也可以在布局上面添加其他控件,甚至我们可以这样做


想必经过本文的介绍,各位现在已经能够模仿写出之前在本文开始的时候列举的那些APP的ActionBar了吧。

2 0