仿ios状态栏颜色和标题栏颜色一致的实例代码
作者:慢慢哈皮
下面小编就为大家分享一篇仿ios状态栏颜色和标题栏颜色一致的实例代码,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
首先创建一个工具类
import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.os.Build; import android.support.v4.content.ContextCompat; import android.view.View; import android.view.ViewGroup; public class StatusBarCompat { private static final int INVALID_VAL = -1; //判断版本 @TargetApi(Build.VERSION_CODES.LOLLIPOP) public static View compat(Activity activity, int statusColor) { //默认颜色 int color = ContextCompat.getColor(activity, R.color.colorPrimaryDark); //若果版本大于等于21 给状态栏设置颜色 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (statusColor != INVALID_VAL) { color = statusColor; } activity.getWindow().setStatusBarColor(color); return null; } //如果版本在大于等于19小于21 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { //获取contentView ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content); if (statusColor != INVALID_VAL) { color = statusColor; } //获取contentView里的第一个view 也就是状态栏 View statusBarView = contentView.getChildAt(0); if (statusBarView != null && statusBarView.getMeasuredHeight() == getStatusBarHeight(activity)) { statusBarView.setBackgroundColor(color); return statusBarView; } statusBarView = new View(activity); ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(activity)); statusBarView.setBackgroundColor(color); contentView.addView(statusBarView, lp); return statusBarView; } return null; } public static void compat(Activity activity) { compat(activity, INVALID_VAL); } 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; } }
然后在activity里调用方法
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v4.content.ContextCompat; import android.os.Build; import android.view.WindowManager; public class MainActivity extends AppCompatActivity { protected boolean statusBarCompat = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (statusBarCompat) { StatusBarCompat.compat(this, ContextCompat.getColor(this, R.color.colorPrimary)); transparent19and20(); } } protected void transparent19and20() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } } }
抄的别人的 网上一大堆,作者不要来喷我,我是为了自己以后好找到使用。
以上这篇仿ios状态栏颜色和标题栏颜色一致的实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。