优雅地实现 Android Toolbar 及沉浸式状态栏

在某些系统上主页面和状态栏存在两种极不搭的画风,处女座看了一定会很难受,不要问我怎么知道的,你猜啊!~猜啊~
前戏有了,哦不,需求,那么现在直入主题,让我们帮助处女座脱离苦海。

例子用了Toolbar,需要依赖support-v7

去除Actionbar

为方便地去除Actionbar,采用了自定义theme继承
“Theme.AppCompat.Light.NoActionBar”的方案


    <style name="CAppTheme" parent="Theme.AppCompat.Light.NoActionBar">

AndroidManifest.xml中修改

".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/CAppTheme">

Toolbar布局

include_layout_toolbar.xml


<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    style="@style/mToolbarStyle"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:background="@color/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/tb_left_tv"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentLeft="true"
            android:gravity="center"
            android:text="" />

        <TextView
            android:id="@+id/tb_center_tv"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:text="@string/app_name" />

        <TextView
            android:id="@+id/tb_right_tv"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_alignParentRight="true"
            android:gravity="center"
            android:text="" />
    RelativeLayout>
android.support.v7.widget.Toolbar>

自定义Toolbar Style解决左边留白的问题

通过观察源码,发现是contentInsetStart在作怪,fix it!

    
    <style name="mToolbarStyle" parent="@style/Widget.AppCompat.Toolbar">

        -- 设置该属性解决Toolbar左边空白 -->
        <item name="contentInsetStart">0dpitem>
    style>

BaseActivity

public class BaseActivity extends AppCompatActivity {
    private static final String TAG = "BaseActivity";
    /**
     * Root view
     */
    private LinearLayout mRootLayout;
    /**
     * Toolbar instance
     */
    protected Toolbar mToolbar;

    public Toolbar getToolbar() {
        return mToolbar;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.activity_base);
        if (!isTaskRoot()) {
        /* If this is not the root activity,finish it.*/
            Intent intent = getIntent();
            String action = intent.getAction();
            if (intent.hasCategory(Intent.CATEGORY_LAUNCHER) && Intent.ACTION_MAIN.equals(action)) {
                //Logger.w("Activity is not the root.  Finishing Activity instead of launching.");
                Log.w(TAG, "Activity is not the root.  Finishing Activity instead of launching.");
                finish();
                return;
            }
        }
    }

    @Override
    public void setContentView(int layoutId) {
        setContentView(View.inflate(this, layoutId, null));
    }

    @Override
    public void setContentView(View view) {
        mRootLayout = (LinearLayout) findViewById(R.id.root_layout);
        if (mRootLayout == null) {
            return;
        }
        mRootLayout.addView(view,
                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        initToolbar();
    }

    /**
     * 初始化Toolbar
     */
    private void initToolbar() {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        if (mToolbar != null) {
            showToolbar(true);
            //mToolbar.inflateMenu(R.menu.main);
            /** 设置支持ActionBar,当然也可以不这样做 */
            //setSupportActionBar(mToolbar);
            /** 去除ActionBar默认Title显示 */
            //getSupportActionBar().setDisplayShowTitleEnabled(false);
        }
    }

    /**
     * 显示Toolbar
     *
     * @param show true:显示,false:隐藏
     */
    public void showToolbar(boolean show) {
        if (mToolbar == null) {
            Log.e(TAG, "Toolbar is null.");
        } else {
            int paddingTop = mToolbar.getPaddingTop();
            int paddingBottom = mToolbar.getPaddingBottom();
            int paddingLeft = mToolbar.getPaddingLeft();
            int paddingRight = mToolbar.getPaddingRight();
            int statusHeight = ScreenUtil.getStatusHeight(this);
            ViewGroup.LayoutParams params = mToolbar.getLayoutParams();
            int height = params.height;
            /**
             * 利用状态栏的高度,4.4及以上版本给Toolbar设置一个paddingTop值为status_bar的高度,
             * Toolbar延伸到status_bar顶部
             **/
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                setTranslucentStatus(show);
                if (show) {
                    paddingTop += statusHeight;
                    height += statusHeight;
                } else {
                    paddingTop -= statusHeight;
                    height -= statusHeight;
                }
            }
            params.height = height;
            mToolbar.setPadding(paddingLeft, paddingTop, paddingRight, paddingBottom);
            mToolbar.setVisibility(show ? View.VISIBLE : View.GONE);
        }
    }

    /**
     * 设置透明状态栏
     * 对4.4及以上版本有效
     *
     * @param on
     */
    @TargetApi(Build.VERSION_CODES.KITKAT)
    private void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }
}

获取状态栏高度

   /**
     * 获得状态栏的高度
     *
     * @param context
     * @return px
     */
    public static int getStatusHeight(Context context) {

        int statusHeight = -1;
        try {
            Class clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height").get(object).toString());
            statusHeight = context.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusHeight;
    }

BaseActivity布局

activity_base.xml


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <include layout="@layout/include_layout_toolbar" />

LinearLayout>

MainActivity

public class MainActivity extends BaseActivity implements OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
        }
    }
}

MainActivity布局

activity_main.xml

"http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.elonlink.demo.MainActivity">

</RelativeLayout>

你可能感兴趣的:(Android)