优雅地实现 Android Toolbar 及沉浸式状态栏
博客专区 > XngPro 的博客 > 博客详情
优雅地实现 Android Toolbar 及沉浸式状态栏
XngPro 发表于11个月前
优雅地实现 Android Toolbar 及沉浸式状态栏
  • 发表于 11个月前
  • 阅读 17
  • 收藏 0
  • 点赞 0
  • 评论 0

标题:腾讯云 新注册用户域名抢购1元起>>>   

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

去除 Actionbar

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

<!--Custom base application theme-->
    <style name="CAppTheme" parent="Theme.AppCompat.Light.NoActionBar">

AndroidManifest.xml中修改

<application
        android:name=".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

<?xml version="1.0" encoding="utf-8"?>
<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!

    <!--Custom Toolbar Style -->
    <style name="mToolbarStyle" parent="@style/Widget.AppCompat.Toolbar"> <!-- 设置该属性解决Toolbar左边空白 --> <item name="contentInsetStart">0dp</item> </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

<?xml version="1.0" encoding="utf-8"?>
<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

<RelativeLayout xmlns:android="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> 
共有 人打赏支持
粉丝 0
博文 36
码字总数 8369
×
XngPro
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: