Android实现4.4以上系统状态栏透明。
原理:
4.4以上Android提供了设置状态栏背景透明的接口,我们直接使用相关代码即可实现。但是状态栏透明后所有的窗口内所有内容都是从顶部开始的,并未从状态栏底部开始。所以我们可以采用加入一个线性布局,添加一个View占掉顶部状态栏的位置。这样我们就可以从状态栏底部开始布局。不过有一个坏处就是整个根布局是线性的。
import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.util.AttributeSet;
import android.view.View;
import android.view.WindowManager;
/**
* 自定义的状态栏,用于占状态栏的位
*
* @author luodo
*
*/
public class StatusBar extends View {
private int width;
private int height;
private Activity activity;
public StatusBar(Context context, AttributeSet attrs) {
super( context, attrs);
activity = (Activity) context;
WindowManager wm = (WindowManager) context
.getSystemService(Context. WINDOW_SERVICE);
width = wm.getDefaultDisplay(). getWidth();
if (VERSION. SDK_INT >= VERSION_CODES. KITKAT) {
activity.getWindow().addFlags( WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
activity.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
height = getStatusHeight( activity);
} else {
height = 0;
} }
@Override
protected void onMeasure( int widthMeasureSpec, int heightMeasureSpec) {
System. out.println( height);
setMeasuredDimension( width, height);
}
/**
* 获得状态栏的高度
* @param activity
* @return > 0 success; <= 0 fail
*/
public int getStatusHeight(Activity activity) {
int statusHeight = 0;
Rect localRect = new Rect();
activity.getWindow().getDecorView()
.getWindowVisibleDisplayFrame( localRect);
statusHeight = localRect. top;
if (0 == statusHeight) {
Class<?> localClass;
try {
localClass = Class.forName("com.android.internal.R$dimen");
Object localObject = localClass.newInstance();
int i5 = Integer. parseInt(localClass
.getField( "status_bar_height").get( localObject)
.toString());
statusHeight = activity.getResources()
.getDimensionPixelSize( i5);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
}
return statusHeight;
}
}
使用方法:
![这里写图片描述](https://img-blog.csdn.net/20150804141832277)
可以让StatusBar在4.4系统以上显示,高度为系统的状态栏高度。4.4以下显示高度为0