关于Android4.4及以上状态栏渲染那点事

来源:互联网 发布:云墙vpn for mac 编辑:程序博客网 时间:2024/05/17 20:42

关键代码:
//渲染状态栏
// requestWindowFeature(Window.FEATURE_NO_TITLE);
//通知栏设为透明 android系统4.4以上才有效
// getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

上面两句代码放入Activity的onCreate(Bundle savedInstanceState)方法里,并且放在setContentView(R.layout.activity_main)之前就行了;

代码示例:`

@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    requestWindowFeature(Window.FEATURE_NO_TITLE);    //通知栏设为透明  android系统4.4以上才有效    getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);    //标题栏渐变    setContentView(R.layout.activity_redering);    TextView tv = (TextView) findViewById(R.id.tv);    LinearLayout root = (LinearLayout) findViewById(R.id.ll_reder);    LinearLayout.LayoutParams pas = (LinearLayout.LayoutParams) root.getLayoutParams();    tv.setPadding(0, getStatusBarHeight(this), 0, 0);    //pas.setMargins(0, getStatusBarHeight(this), 0, 0);}//返回状态栏高度public static int getStatusBarHeight(Context context){    Class<?> c = null;    Object obj = null;    Field field = null;    int x = 0, statusBarHeight = 0;    try {        c = Class.forName("com.android.internal.R$dimen");        obj = c.newInstance();        field = c.getField("status_bar_height");        x = Integer.parseInt(field.get(obj).toString());        statusBarHeight = context.getResources().getDimensionPixelSize(x);    } catch (Exception e1) {        e1.printStackTrace();    }    return statusBarHeight;}

`

布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/ll_reder"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff00ff">
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Good" />
</LinearLayout>
</LinearLayout>

之所以会用LinearLayout嵌套一个LinearLayout,是想测试渲染效果,也就是说
如果不设置:tv.setPadding(0, getStatusBarHeight(this), 0, 0);
顶部状态栏效果如下图(顶部状态栏将悬浮在布局之上):
未设置padding或margins

设置:tv.setPadding(0, getStatusBarHeight(this), 0, 0);
顶部状态栏效果如下图(顶部状态栏为tv的背景色):
设置padding

设置:pas.setMargins(0, getStatusBarHeight(this), 0, 0);
顶部状态栏效果如下图(顶部状态栏为灰白):
设置setMargins

最后来个原始的对比看看效果:
原始图片

1 0
原创粉丝点击