安卓沉浸透明状态栏导航栏

Android 系统自4.2 开始 UI 上就没多大改变,4.4 也只是增加了透明状态栏与导航栏的功能,如图

使用这个特性能开发出很漂亮的UI,尤其对于 google 原生系统,屏幕下方的导航栏白白占据一块屏幕空间,看起来很不爽

方法 1:

在activity中加入红色部分
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    //透明导航栏
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
    setContentView(R.layout.activity_main);// 关联布局文件
}
方法2:直接修改app样式
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="android:windowTranslucentStatus">true</item>
    <item name="android:windowTranslucentNavigation">true</item>
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

做完以上操作会发现空间会到状态栏上去   如图



很明显 google 的意图是使你的 view 可以占据整个屏幕,然后 状态栏和导航栏 透明覆盖在上面很明显这样不可行。
那有没有办法使你的 view 保持原来大小呢?
有,你需要在这个 activity 的 layout xml 文件添加两个属性

  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2.     android:layout_width="fill_parent"
  3.     android:layout_height="fill_parent"
  4.     android:gravity="center_horizontal"
  5.     android:fitsSystemWindows="true"
  6.     android:clipToPadding="true"
  7.     android:orientation="vertical" >


这样状态栏的背景就是你的 activity 的主背景,倘若actionbar 在,将会很难看,会多出来很大一块 事实证明,google 并没有提供一个比较好的解决方案,他的 透明状态栏与导航栏的应用局限于,全屏阅读文字或玩游戏那种情景,

有时候我们又需要控件可以上去,旁边的又在下面怎么办?

 

我想到了在上面加个与状态栏一样高的控件,考虑到所有手机状态栏高度不一
需要动态获取
View statusBarView = new View(activity);
ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
        getStatusBarHeight(activity));
statusBarView.setBackgroundColor(Color.parseColor("#FF0000"));
contentView.addView(statusBarView, lp);


public static int getStatusBarHeight(Context context)
{
    int result = 0;
    int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0)
    {
        result = context.getResources().getDimensionPixelSize(resourceId);
    }
    return result;
}
原理很簡單,就是在頂部加上一個于狀態欄一樣高的view 這樣就可以了
好了,就説到這了,歡迎一起探討

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值