美文网首页
2019-02-13

2019-02-13

作者: 遥望星空forward | 来源:发表于2019-02-13 00:48 被阅读0次

Android状态栏工具类

​ 基本上每个APP的状态栏都设置为了沉浸式状态栏,在这里我集合了一个状态栏工具类,基本上能适合大部分APP的设置,支持4.4以上状态栏的颜色设置,6.0及以上以及6.0以下部分小米和魅族手机可以设置为白底黑字,所以我在这里分享出来,一来为自己做下记录,二来希望能够帮助他人。好了,下面贴下代码,在代码中都有较为详细的注释了,这里就不啰嗦那么多了。

StatusBarUtil

public class StatusBarUtil
{
   /**
    * 修改状态栏为全透明
    *
    * @param activity
    */
   public static void transparencyBar(Activity activity)
   {
      if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
      {
         Window window = activity.getWindow();
         window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
         window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
         window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
         window.setStatusBarColor(Color.TRANSPARENT);

      }
      else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
      {
         Window window = activity.getWindow();
         window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
      }
   }

   /**
    * 透明状态栏和导航栏
    *
    * @param activity
    */
   public static void transparencyStatusBarAndNavigationBar(Activity activity)
   {

      if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
      {
         //透明状态栏
         activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
         //透明导航栏
         activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
      }
   }

   /**
    * 生成虚拟状态栏
    *
    * @param activity
    * @param color    背景颜色
    * @param alpha    透明度
    */
   public static TextView createView(Activity activity, @ColorInt int color, float alpha)
   {
      TextView textView = new TextView(activity);
      textView.setBackgroundColor(color);
      textView.setAlpha(alpha);
      textView.setId(getId());
      RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(activity));
      textView.setLayoutParams(layoutParams);
      return textView;
   }

   public static int getId()
   {
      return R.id.statusbarutil_fake_status_bar_view;
   }

   /**
    * 添加状态栏
    *
    * @param activity
    * @param color    背景颜色
    * @param alpha    透明度
    */
   public static void addStatusBarViewAlpha(Activity activity, @ColorInt int color, float alpha)
   {
      transparencyBar(activity);
      TextView textView = new TextView(activity);
      textView.setBackgroundColor(color);
      textView.setAlpha(alpha);
      textView.setId(getId());
      RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(activity));
      textView.setLayoutParams(layoutParams);
      ViewGroup decorView = (ViewGroup)activity.getWindow().getDecorView();
      decorView.addView(textView);
   }

   /**
    * 添加状态栏
    *
    * @param activity
    * @param color    背景颜色
    * @param alpha    透明度
    */
   public static void addStatusBarView(Activity activity, @ColorInt int color, int alpha)
   {
      transparencyBar(activity);
      TextView textView = new TextView(activity);
      textView.setBackgroundColor(calculateStatusColor(color, alpha));
      textView.setId(getId());
      RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight(activity));
      textView.setLayoutParams(layoutParams);
      ViewGroup decorView = (ViewGroup)activity.getWindow().getDecorView();
      decorView.addView(textView);
   }

   /**
    * 显示或者隐藏状态栏
    *
    * @param activity
    * @param show
    */
   public static void hideStatusBar(Activity activity, boolean show)
   {
      ViewGroup decorView = (ViewGroup)activity.getWindow().getDecorView();
      View view = decorView.findViewById(getId());
      if(view == null)
      {
         return;
      }
      if(show)
      {
         view.setVisibility(View.VISIBLE);
      }
      else
      {
         view.setVisibility(View.GONE);
      }
   }

   /**
    * 状态栏设置为沉浸式
    *
    * @param activity
    */
   public static void immersionStatusBar(Activity activity)
   {
//        activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN|WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, WindowManager.LayoutParams.FLAG_FULLSCREEN);
      activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
      if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
      {
         activity.getWindow().setNavigationBarColor(Color.TRANSPARENT);
      }
   }

   /**
    * 修改状态栏颜色,支持4.4以上版本
    *
    * @param activity
    * @param color
    */
   public static void setStatusBarColor(Activity activity, int color)
   {
      if(color == 0)
      {
         return;
      }
      if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
      {
         Window window = activity.getWindow();
         //      window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
         window.setStatusBarColor(color);
      }
      else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
      {
         //使用SystemBarTint库使4.4版本状态栏变色,需要先将状态栏设置为透明
         transparencyBar(activity);
         SystemBarTintManager tintManager = new SystemBarTintManager(activity);
         tintManager.setStatusBarTintEnabled(true);
         tintManager.setStatusBarTintResource(color);
      }
   }


   /**
    * 状态栏亮色模式,设置状态栏黑色文字、图标,
    * 适配4.4以上版本MIUIV、Flyme和6.0以上版本其他Android
    *
    * @param activity
    * @return 1:MIUUI 2:Flyme 3:android6.0
    */
   public static int StatusBarLightMode(Activity activity)
   {
      if(!confirmFourUp())
      {
         return -1;
      }
      else
      {
         int result = 0;
         if(MIUISetStatusBarLightMode(activity, true))
         {
            result = 1;
         }
         else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
         {
            activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            result = 3;
         }
         else
         {
            setStatusBarColor(activity, R.color.black);
            result = 4;
         }
         return result;
      }
   }

   /**
    * 已知系统类型时,设置状态栏黑色文字、图标。
    * 适配4.4以上版本MIUIV、Flyme和6.0以上版本其他Android
    *
    * @param activity
    * @param type     1:MIUUI 2:Flyme 3:android6.0
    */
   public static void StatusBarLightMode(Activity activity, int type)
   {
      if(type == 1)
      {
         MIUISetStatusBarLightMode(activity, true);
      }
      else if(type == 2)
      {
         FlymeSetStatusBarLightMode(activity.getWindow(), true);
      }
      else if(type == 3)
      {
         activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
      }
   }

   /**
    * 状态栏暗色模式,清除MIUI、flyme或6.0以上版本状态栏黑色文字、图标tt
    */
   public static void StatusBarDarkMode(Activity activity, int type)
   {
      if(type == 1)
      {
         MIUISetStatusBarLightMode(activity, false);
      }
      else if(type == 2)
      {
         FlymeSetStatusBarLightMode(activity.getWindow(), false);
      }
      else if(type == 3)
      {
         activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
      }
   }


   /**
    * 状态栏暗色模式,清除MIUI、flyme或6.0以上版本状态栏黑色文字、图标tt
    */
   public static int StatusBarDarkMode(Activity activity)
   {
      if(!confirmFourUp())
      {
         return -1;
      }
      if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
      {
         if(isMIUI())
         {
            MIUISetStatusBarLightMode(activity, false);
            return 1;
         }
         else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
         {
            activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            return 3;
         }
      }
      setSocialityStatusBar(activity);
      return 0;
   }

   /**
    * 设置状态栏图标为深色和魅族特定的文字风格
    * 可以用来判断是否为Flyme用户
    *
    * @param window 需要设置的窗口
    * @param dark   是否把状态栏文字及图标颜色设置为深色
    * @return boolean 成功执行返回true
    */
   public static boolean FlymeSetStatusBarLightMode(Window window, boolean dark)
   {
      boolean result = false;
      if(window != null)
      {
         try
         {
            WindowManager.LayoutParams lp = window.getAttributes();
            Field darkFlag = WindowManager.LayoutParams.class.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
            Field meizuFlags = WindowManager.LayoutParams.class.getDeclaredField("meizuFlags");
            darkFlag.setAccessible(true);
            meizuFlags.setAccessible(true);
            int bit = darkFlag.getInt(null);
            int value = meizuFlags.getInt(lp);
            if(dark)
            {
               value |= bit;
            }
            else
            {
               value &= ~bit;
            }
            meizuFlags.setInt(lp, value);
            window.setAttributes(lp);
            result = true;
         }
         catch(Exception e)
         {

         }
      }
      return result;
   }

   /**
    * 需要MIUIV6以上
    *
    * @param activity
    * @param dark     是否把状态栏文字及图标颜色设置为深色
    * @return boolean 成功执行返回true
    */
   public static boolean MIUISetStatusBarLightMode(Activity activity, boolean dark)
   {
      boolean result = false;
      Window window = activity.getWindow();
      if(window != null)
      {
         Class clazz = window.getClass();
         try
         {
            int darkModeFlag = 0;
            Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            if(dark)
            {
               extraFlagField.invoke(window, darkModeFlag, darkModeFlag);//状态栏透明且黑色字体
            }
            else
            {
               extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
            }
            result = true;

            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            {
               //开发版 7.7.13 及以后版本采用了系统API,旧方法无效但不会报错,所以两个方式都要加上
               if(dark)
               {
                  activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
               }
               else
               {
                  activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
               }
            }
         }
         catch(Exception e)
         {

         }
      }
      return result;
   }

   /**
    * 获取状态栏高度
    *
    * @param context context
    * @return 状态栏高度
    */
   public static int getStatusBarHeight(Context context)
   {
      if(!confirmFourUp())
      {
         return 0;
      }
      // 获得状态栏高度
      int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
      return context.getResources().getDimensionPixelSize(resourceId);
   }

   /**
    * 计算状态栏颜色
    * <p>
    * eg :View.setBackgroundColor(calculateStatusColor(color, alpha));
    *
    * @param color color值
    * @param alpha alpha值
    * @return 最终的状态栏颜色
    */
   private static int calculateStatusColor(@ColorInt int color, int alpha)
   {
      if(alpha == 0)
      {
         return color;
      }
      float a = 1 - alpha / 255f;
      int red = color >> 16 & 0xff;
      int green = color >> 8 & 0xff;
      int blue = color & 0xff;
      red = (int)(red * a + 0.5);
      green = (int)(green * a + 0.5);
      blue = (int)(blue * a + 0.5);
      return 0xff << 24 | red << 16 | green << 8 | blue;
   }

   /**
    * 退出全屏
    *
    * @param activity
    */
   public static void quitFullScreen(Activity activity)
   {
      activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
   }

   /**
    * 设置全屏
    *
    * @param activity
    */
   public static void setFullScreen(Activity activity)
   {
      activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
   }

   /**
    * 判断手机版本是否是4.4以上
    *
    * @return
    */
   public static boolean confirmFourUp()
   {
      return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
   }

   /**
    * 状态栏--白底黑字  适配6.0及以上
    * 6.0一下状态栏设置为黑色
    *
    * @param activity
    */
   public static void setSocialityStatusBar(Activity activity)
   {

      if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
      {
         transparencyBar(activity);
         StatusBarLightMode(activity);
//       setStatusBarColor(activity, activity.getResources().getColor(R.color.white));
         View rootView = ((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0);
         rootView.setPadding(0, getStatusBarHeight(activity), 0, 0);
      }
      else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
      {
         setStatusBarColor(activity, R.color.black);
      }
   }

   // 检测是否是小米手机MIUI
   private static final String KEY_MIUI_VERSION_CODE = "ro.miui.ui.version.code";
   private static final String KEY_MIUI_VERSION_NAME = "ro.miui.ui.version.name";
   private static final String KEY_MIUI_INTERNAL_STORAGE = "ro.miui.internal.storage";

   public static boolean isMIUI()
   {
      Properties prop = new Properties();
      boolean isMIUI;
      try
      {
         prop.load(new FileInputStream(new File(Environment.getRootDirectory(), "build.prop")));
      }
      catch(IOException e)
      {
         e.printStackTrace();
         return false;
      }
      isMIUI = prop.getProperty(KEY_MIUI_VERSION_CODE, null) != null || prop.getProperty(KEY_MIUI_VERSION_NAME, null) != null || prop.getProperty(KEY_MIUI_INTERNAL_STORAGE, null) != null;
      return isMIUI;
   }

   public static void setMainStatusBar(Activity activity)
   {
      if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
      {
         StatusBarUtil.transparencyBar(activity);
         View rootView = ((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0);
         rootView.setPadding(0, getStatusBarHeight(activity), 0, 0);
      }
   }

   public static void setSocialStatusBar(Activity activity)
   {
      if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
      {
         StatusBarUtil.transparencyBar(activity);
         View rootView = ((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0);
         rootView.setPadding(0, getStatusBarHeight(activity), 0, 0);
      }
      StatusBarLightMode(activity);
   }
}

ids.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <item name="statusbarutil_fake_status_bar_view" type="id"/>
</resources>

SystemBarTintManager

官方在4.4版本只提供了状态栏透明的api,大家普遍采用开源库SystemBarTint

public class SystemBarTintManager {
    static {
        // Android allows a system property to override the presence of the navigation bar.
        // Used by the emulator.
        // See https://github.com/android/platform_frameworks_base/blob/master/policy/src/com/android/internal/policy/impl/PhoneWindowManager.java#L1076
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                Class c = Class.forName("android.os.SystemProperties");
                Method m = c.getDeclaredMethod("get", String.class);
                m.setAccessible(true);
                sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys");
            } catch (Throwable e) {
                sNavBarOverride = null;
            }
        }
    }


    /**
     * The default system bar tint color value.
     */
    public static final int DEFAULT_TINT_COLOR = 0x99000000;

    private static String sNavBarOverride;

    private final SystemBarConfig mConfig;
    private boolean mStatusBarAvailable;
    private boolean mNavBarAvailable;
    private boolean mStatusBarTintEnabled;
    private boolean mNavBarTintEnabled;
    private View mStatusBarTintView;
    private View mNavBarTintView;

    /**
     * Constructor. Call this in the host activity onCreate method after its
     * content view has been set. You should always create new instances when
     * the host activity is recreated.
     *
     * @param activity The host activity.
     */
    @TargetApi(19)
    public SystemBarTintManager(Activity activity) {

        Window win = activity.getWindow();
        ViewGroup decorViewGroup = (ViewGroup) win.getDecorView();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // check theme attrs
            int[] attrs = {android.R.attr.windowTranslucentStatus,
                    android.R.attr.windowTranslucentNavigation};
            TypedArray a = activity.obtainStyledAttributes(attrs);
            try {
                mStatusBarAvailable = a.getBoolean(0, false);
                mNavBarAvailable = a.getBoolean(1, false);
            } finally {
                a.recycle();
            }

            // check window flags
            WindowManager.LayoutParams winParams = win.getAttributes();
            int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            if ((winParams.flags & bits) != 0) {
                mStatusBarAvailable = true;
            }
            bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
            if ((winParams.flags & bits) != 0) {
                mNavBarAvailable = true;
            }
        }

        mConfig = new SystemBarConfig(activity, mStatusBarAvailable, mNavBarAvailable);
        // device might not have virtual navigation keys
        if (!mConfig.hasNavigtionBar()) {
            mNavBarAvailable = false;
        }

        if (mStatusBarAvailable) {
            setupStatusBarView(activity, decorViewGroup);
        }
        if (mNavBarAvailable) {
            setupNavBarView(activity, decorViewGroup);
        }

    }

    /**
     * Enable tinting of the system status bar.
     *
     * If the platform is running Jelly Bean or earlier, or translucent system
     * UI modes have not been enabled in either the theme or via window flags,
     * then this method does nothing.
     *
     * @param enabled True to enable tinting, false to disable it (default).
     */
    public void setStatusBarTintEnabled(boolean enabled) {
        mStatusBarTintEnabled = enabled;
        if (mStatusBarAvailable) {
            mStatusBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE);
        }
    }

    /**
     * Enable tinting of the system navigation bar.
     *
     * If the platform does not have soft navigation keys, is running Jelly Bean
     * or earlier, or translucent system UI modes have not been enabled in either
     * the theme or via window flags, then this method does nothing.
     *
     * @param enabled True to enable tinting, false to disable it (default).
     */
    public void setNavigationBarTintEnabled(boolean enabled) {
        mNavBarTintEnabled = enabled;
        if (mNavBarAvailable) {
            mNavBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE);
        }
    }

    /**
     * Apply the specified color tint to all system UI bars.
     *
     * @param color The color of the background tint.
     */
    public void setTintColor(int color) {
        setStatusBarTintColor(color);
        setNavigationBarTintColor(color);
    }

    /**
     * Apply the specified drawable or color resource to all system UI bars.
     *
     * @param res The identifier of the resource.
     */
    public void setTintResource(int res) {
        setStatusBarTintResource(res);
        setNavigationBarTintResource(res);
    }

    /**
     * Apply the specified drawable to all system UI bars.
     *
     * @param drawable The drawable to use as the background, or null to remove it.
     */
    public void setTintDrawable(Drawable drawable) {
        setStatusBarTintDrawable(drawable);
        setNavigationBarTintDrawable(drawable);
    }

    /**
     * Apply the specified alpha to all system UI bars.
     *
     * @param alpha The alpha to use
     */
    public void setTintAlpha(float alpha) {
        setStatusBarAlpha(alpha);
        setNavigationBarAlpha(alpha);
    }

    /**
     * Apply the specified color tint to the system status bar.
     *
     * @param color The color of the background tint.
     */
    public void setStatusBarTintColor(int color) {
        if (mStatusBarAvailable) {
            mStatusBarTintView.setBackgroundColor(color);
        }
    }

    /**
     * Apply the specified drawable or color resource to the system status bar.
     *
     * @param res The identifier of the resource.
     */
    public void setStatusBarTintResource(int res) {
        if (mStatusBarAvailable) {
            mStatusBarTintView.setBackgroundResource(res);
        }
    }

    /**
     * Apply the specified drawable to the system status bar.
     *
     * @param drawable The drawable to use as the background, or null to remove it.
     */
    @SuppressWarnings("deprecation")
    public void setStatusBarTintDrawable(Drawable drawable) {
        if (mStatusBarAvailable) {
            mStatusBarTintView.setBackgroundDrawable(drawable);
        }
    }

    /**
     * Apply the specified alpha to the system status bar.
     *
     * @param alpha The alpha to use
     */
    @TargetApi(11)
    public void setStatusBarAlpha(float alpha) {
        if (mStatusBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mStatusBarTintView.setAlpha(alpha);
        }
    }

    /**
     * Apply the specified color tint to the system navigation bar.
     *
     * @param color The color of the background tint.
     */
    public void setNavigationBarTintColor(int color) {
        if (mNavBarAvailable) {
            mNavBarTintView.setBackgroundColor(color);
        }
    }

    /**
     * Apply the specified drawable or color resource to the system navigation bar.
     *
     * @param res The identifier of the resource.
     */
    public void setNavigationBarTintResource(int res) {
        if (mNavBarAvailable) {
            mNavBarTintView.setBackgroundResource(res);
        }
    }

    /**
     * Apply the specified drawable to the system navigation bar.
     *
     * @param drawable The drawable to use as the background, or null to remove it.
     */
    @SuppressWarnings("deprecation")
    public void setNavigationBarTintDrawable(Drawable drawable) {
        if (mNavBarAvailable) {
            mNavBarTintView.setBackgroundDrawable(drawable);
        }
    }

    /**
     * Apply the specified alpha to the system navigation bar.
     *
     * @param alpha The alpha to use
     */
    @TargetApi(11)
    public void setNavigationBarAlpha(float alpha) {
        if (mNavBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mNavBarTintView.setAlpha(alpha);
        }
    }

    /**
     * Get the system bar configuration.
     *
     * @return The system bar configuration for the current device configuration.
     */
    public SystemBarConfig getConfig() {
        return mConfig;
    }

    /**
     * Is tinting enabled for the system status bar?
     *
     * @return True if enabled, False otherwise.
     */
    public boolean isStatusBarTintEnabled() {
        return mStatusBarTintEnabled;
    }

    /**
     * Is tinting enabled for the system navigation bar?
     *
     * @return True if enabled, False otherwise.
     */
    public boolean isNavBarTintEnabled() {
        return mNavBarTintEnabled;
    }

    private void setupStatusBarView(Context context, ViewGroup decorViewGroup) {
        mStatusBarTintView = new View(context);
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, mConfig.getStatusBarHeight());
        params.gravity = Gravity.TOP;
        if (mNavBarAvailable && !mConfig.isNavigationAtBottom()) {
            params.rightMargin = mConfig.getNavigationBarWidth();
        }
        mStatusBarTintView.setLayoutParams(params);
        mStatusBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR);
        mStatusBarTintView.setVisibility(View.GONE);
        decorViewGroup.addView(mStatusBarTintView);
    }

    private void setupNavBarView(Context context, ViewGroup decorViewGroup) {
        mNavBarTintView = new View(context);
        LayoutParams params;
        if (mConfig.isNavigationAtBottom()) {
            params = new LayoutParams(LayoutParams.MATCH_PARENT, mConfig.getNavigationBarHeight());
            params.gravity = Gravity.BOTTOM;
        } else {
            params = new LayoutParams(mConfig.getNavigationBarWidth(), LayoutParams.MATCH_PARENT);
            params.gravity = Gravity.RIGHT;
        }
        mNavBarTintView.setLayoutParams(params);
        mNavBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR);
        mNavBarTintView.setVisibility(View.GONE);
        decorViewGroup.addView(mNavBarTintView);
    }

    /**
     * Class which describes system bar sizing and other characteristics for the current
     * device configuration.
     *
     */
    public static class SystemBarConfig {

        private static final String STATUS_BAR_HEIGHT_RES_NAME = "status_bar_height";
        private static final String NAV_BAR_HEIGHT_RES_NAME = "navigation_bar_height";
        private static final String NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME = "navigation_bar_height_landscape";
        private static final String NAV_BAR_WIDTH_RES_NAME = "navigation_bar_width";
        private static final String SHOW_NAV_BAR_RES_NAME = "config_showNavigationBar";

        private final boolean mTranslucentStatusBar;
        private final boolean mTranslucentNavBar;
        private final int mStatusBarHeight;
        private final int mActionBarHeight;
        private final boolean mHasNavigationBar;
        private final int mNavigationBarHeight;
        private final int mNavigationBarWidth;
        private final boolean mInPortrait;
        private final float mSmallestWidthDp;

        private SystemBarConfig(Activity activity, boolean translucentStatusBar, boolean traslucentNavBar) {
            Resources res = activity.getResources();
            mInPortrait = (res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);
            mSmallestWidthDp = getSmallestWidthDp(activity);
            mStatusBarHeight = getInternalDimensionSize(res, STATUS_BAR_HEIGHT_RES_NAME);
            mActionBarHeight = getActionBarHeight(activity);
            mNavigationBarHeight = getNavigationBarHeight(activity);
            mNavigationBarWidth = getNavigationBarWidth(activity);
            mHasNavigationBar = (mNavigationBarHeight > 0);
            mTranslucentStatusBar = translucentStatusBar;
            mTranslucentNavBar = traslucentNavBar;
        }

        @TargetApi(14)
        private int getActionBarHeight(Context context) {
            int result = 0;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                TypedValue tv = new TypedValue();
                context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true);
                result = TypedValue.complexToDimensionPixelSize(tv.data, context.getResources().getDisplayMetrics());
            }
            return result;
        }

        @TargetApi(14)
        private int getNavigationBarHeight(Context context) {
            Resources res = context.getResources();
            int result = 0;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                if (hasNavBar(context)) {
                    String key;
                    if (mInPortrait) {
                        key = NAV_BAR_HEIGHT_RES_NAME;
                    } else {
                        key = NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME;
                    }
                    return getInternalDimensionSize(res, key);
                }
            }
            return result;
        }

        @TargetApi(14)
        private int getNavigationBarWidth(Context context) {
            Resources res = context.getResources();
            int result = 0;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                if (hasNavBar(context)) {
                    return getInternalDimensionSize(res, NAV_BAR_WIDTH_RES_NAME);
                }
            }
            return result;
        }

        @TargetApi(14)
        private boolean hasNavBar(Context context) {
            Resources res = context.getResources();
            int resourceId = res.getIdentifier(SHOW_NAV_BAR_RES_NAME, "bool", "android");
            if (resourceId != 0) {
                boolean hasNav = res.getBoolean(resourceId);
                // check override flag (see static block)
                if ("1".equals(sNavBarOverride)) {
                    hasNav = false;
                } else if ("0".equals(sNavBarOverride)) {
                    hasNav = true;
                }
                return hasNav;
            } else { // fallback
                return !ViewConfiguration.get(context).hasPermanentMenuKey();
            }
        }

        private int getInternalDimensionSize(Resources res, String key) {
            int result = 0;
            int resourceId = res.getIdentifier(key, "dimen", "android");
            if (resourceId > 0) {
                result = res.getDimensionPixelSize(resourceId);
            }
            return result;
        }

        @SuppressLint("NewApi")
        private float getSmallestWidthDp(Activity activity) {
            DisplayMetrics metrics = new DisplayMetrics();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
            } else {
                // TODO this is not correct, but we don't really care pre-kitkat
                activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
            }
            float widthDp = metrics.widthPixels / metrics.density;
            float heightDp = metrics.heightPixels / metrics.density;
            return Math.min(widthDp, heightDp);
        }

        /**
         * Should a navigation bar appear at the bottom of the screen in the current
         * device configuration? A navigation bar may appear on the right side of
         * the screen in certain configurations.
         *
         * @return True if navigation should appear at the bottom of the screen, False otherwise.
         */
        public boolean isNavigationAtBottom() {
            return (mSmallestWidthDp >= 600 || mInPortrait);
        }

        /**
         * Get the height of the system status bar.
         *
         * @return The height of the status bar (in pixels).
         */
        public int getStatusBarHeight() {
            return mStatusBarHeight;
        }

        /**
         * Get the height of the action bar.
         *
         * @return The height of the action bar (in pixels).
         */
        public int getActionBarHeight() {
            return mActionBarHeight;
        }

        /**
         * Does this device have a system navigation bar?
         *
         * @return True if this device uses soft key navigation, False otherwise.
         */
        public boolean hasNavigtionBar() {
            return mHasNavigationBar;
        }

        /**
         * Get the height of the system navigation bar.
         *
         * @return The height of the navigation bar (in pixels). If the device does not have
         * soft navigation keys, this will always return 0.
         */
        public int getNavigationBarHeight() {
            return mNavigationBarHeight;
        }

        /**
         * Get the width of the system navigation bar when it is placed vertically on the screen.
         *
         * @return The width of the navigation bar (in pixels). If the device does not have
         * soft navigation keys, this will always return 0.
         */
        public int getNavigationBarWidth() {
            return mNavigationBarWidth;
        }

        /**
         * Get the layout inset for any system UI that appears at the top of the screen.
         *
         * @param withActionBar True to include the height of the action bar, False otherwise.
         * @return The layout inset (in pixels).
         */
        public int getPixelInsetTop(boolean withActionBar) {
            return (mTranslucentStatusBar ? mStatusBarHeight : 0) + (withActionBar ? mActionBarHeight : 0);
        }

        /**
         * Get the layout inset for any system UI that appears at the bottom of the screen.
         *
         * @return The layout inset (in pixels).
         */
        public int getPixelInsetBottom() {
            if (mTranslucentNavBar && isNavigationAtBottom()) {
                return mNavigationBarHeight;
            } else {
                return 0;
            }
        }

        /**
         * Get the layout inset for any system UI that appears at the right of the screen.
         *
         * @return The layout inset (in pixels).
         */
        public int getPixelInsetRight() {
            if (mTranslucentNavBar && !isNavigationAtBottom()) {
                return mNavigationBarWidth;
            } else {
                return 0;
            }
        }
    }
}

相关文章

网友评论

      本文标题:2019-02-13

      本文链接:https://www.haomeiwen.com/subject/ecaleqtx.html