- 在Activity的onCreate()方法中添加代碼
//設置狀態欄透明
StatusBarUtil.setTranslucentStatus(this);
//設置透明狀態欄的paddingTop為false
setRootViewFitsSystemWindows(this,false);
在使用中經常會遇到圖標和標題欄重疊的情況,可以使用StatusBarHeightView
這個控件填充狀態欄上方的位置
package com.onepilltest.util;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import com.onepilltest.R;
public class StatusBarHeightView extends LinearLayout {
private int statusBarHeight;
private int type;
public StatusBarHeightView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public StatusBarHeightView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
public StatusBarHeightView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr);
init(attrs);
}
private void init(@Nullable AttributeSet attrs) {
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
if(resourceId>0) {
statusBarHeight = getResources().getDimensionPixelSize(resourceId);
}
}else{
//低版本 直接設置0
statusBarHeight = 0;
}
if (attrs != null) {
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.StatusBarHeightView);
type = typedArray.getInt(R.styleable.StatusBarHeightView_use_type, 0);
typedArray.recycle();
}
if (type == 1) {
setPadding(getPaddingLeft(), statusBarHeight, getPaddingRight(), getPaddingBottom());
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (type == 0) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
statusBarHeight);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}