BarUtils.java 21 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
package com.wd.common.utils;

import static android.Manifest.permission.EXPAND_STATUS_BAR;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Build;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.annotation.RequiresPermission;
import androidx.appcompat.app.AppCompatActivity;
import androidx.drawerlayout.widget.DrawerLayout;


import com.wd.common.base.BaseApplication;

import java.lang.reflect.Method;

/**
 * <pre>
 *     author: Blankj
 *     blog  : http://blankj.com
 *     time  : 2016/09/23
 *     desc  : utils about bar
 * </pre>
 */
public final class BarUtils {

  ///////////////////////////////////////////////////////////////////////////
  // status bar
  ///////////////////////////////////////////////////////////////////////////

  private static final String TAG_STATUS_BAR = "TAG_STATUS_BAR";
  private static final String TAG_OFFSET = "TAG_OFFSET";
  private static final int KEY_OFFSET = -123;

  private BarUtils() {
    throw new UnsupportedOperationException("u can't instantiate me...");
  }



  /**
   * Return the status bar's height.
   *
   * @return the status bar's height
   */
  public static int getStatusBarHeight() {
    Resources resources = Resources.getSystem();
    int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
    return resources.getDimensionPixelSize(resourceId);
  }

  /**
   * Set the status bar's visibility.
   *
   * @param activity  The activity.
   * @param isVisible True to set status bar visible, false otherwise.
   */
  public static void setStatusBarVisibility(@NonNull final AppCompatActivity activity,
                                            final boolean isVisible) {
    setStatusBarVisibility(activity.getWindow(), isVisible);
  }

  /**
   * Set the status bar's visibility.
   *
   * @param window    The window.
   * @param isVisible True to set status bar visible, false otherwise.
   */
  public static void setStatusBarVisibility(@NonNull final Window window,
                                            final boolean isVisible) {
    if (isVisible) {
      window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
      showStatusBarView(window);
      addMarginTopEqualStatusBarHeight(window);
    } else {
      window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
      hideStatusBarView(window);
      subtractMarginTopEqualStatusBarHeight(window);
    }
  }

  /**
   * Return whether the status bar is visible.
   *
   * @param activity The activity.
   * @return {@code true}: yes<br>{@code false}: no
   */
  public static boolean isStatusBarVisible(@NonNull final AppCompatActivity activity) {
    int flags = activity.getWindow().getAttributes().flags;
    return (flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) == 0;
  }

  /**
   * Set the status bar's light mode.
   *
   * @param activity    The activity.
   * @param isLightMode True to set status bar light mode, false otherwise.
   */
  public static void setStatusBarLightMode(@NonNull final AppCompatActivity activity,
                                           final boolean isLightMode) {
    setStatusBarLightMode(activity.getWindow(), isLightMode);
  }

  /**
   * Set the status bar's light mode.
   *
   * @param window      The window.
   * @param isLightMode True to set status bar light mode, false otherwise.
   */
  public static void setStatusBarLightMode(@NonNull final Window window,
                                           final boolean isLightMode) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
      View decorView = window.getDecorView();
      if (decorView != null) {
        int vis = decorView.getSystemUiVisibility();
        if (isLightMode) {
          vis |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        } else {
          vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        }
        decorView.setSystemUiVisibility(vis);
      }
    }
  }

  /**
   * Is the status bar light mode.
   *
   * @param activity The activity.
   * @return {@code true}: yes<br>{@code false}: no
   */
  public static boolean isStatusBarLightMode(@NonNull final AppCompatActivity activity) {
    return isStatusBarLightMode(activity.getWindow());
  }

  /**
   * Is the status bar light mode.
   *
   * @param window The window.
   * @return {@code true}: yes<br>{@code false}: no
   */
  public static boolean isStatusBarLightMode(@NonNull final Window window) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
      View decorView = window.getDecorView();
      if (decorView != null) {
        int vis = decorView.getSystemUiVisibility();
        return (vis & View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR) != 0;
      }
    }
    return false;
  }

  /**
   * Add the top margin size equals status bar's height for view.
   *
   * @param view The view.
   */
  public static void addMarginTopEqualStatusBarHeight(@NonNull View view) {
    view.setTag(TAG_OFFSET);
    Object haveSetOffset = view.getTag(KEY_OFFSET);
    if (haveSetOffset != null && (Boolean) haveSetOffset) {
      return;
    }
    MarginLayoutParams layoutParams = (MarginLayoutParams) view.getLayoutParams();
    layoutParams.setMargins(layoutParams.leftMargin,
            layoutParams.topMargin + getStatusBarHeight(),
            layoutParams.rightMargin,
            layoutParams.bottomMargin);
    view.setTag(KEY_OFFSET, true);
  }

  /**
   * Subtract the top margin size equals status bar's height for view.
   *
   * @param view The view.
   */
  public static void subtractMarginTopEqualStatusBarHeight(@NonNull View view) {
    Object haveSetOffset = view.getTag(KEY_OFFSET);
    if (haveSetOffset == null || !(Boolean) haveSetOffset) {
      return;
    }
    MarginLayoutParams layoutParams = (MarginLayoutParams) view.getLayoutParams();
    layoutParams.setMargins(layoutParams.leftMargin,
            layoutParams.topMargin - getStatusBarHeight(),
            layoutParams.rightMargin,
            layoutParams.bottomMargin);
    view.setTag(KEY_OFFSET, false);
  }

  private static void addMarginTopEqualStatusBarHeight(final Window window) {
    View withTag = window.getDecorView().findViewWithTag(TAG_OFFSET);
    if (withTag == null) {
      return;
    }
    addMarginTopEqualStatusBarHeight(withTag);
  }

  private static void subtractMarginTopEqualStatusBarHeight(final Window window) {
    View withTag = window.getDecorView().findViewWithTag(TAG_OFFSET);
    if (withTag == null) {
      return;
    }
    subtractMarginTopEqualStatusBarHeight(withTag);
  }

  /**
   * Set the status bar's color.
   *
   * @param activity The activity.
   * @param color    The status bar's color.
   */
  public static View setStatusBarColor(@NonNull final AppCompatActivity activity,
                                       @ColorInt final int color) {
    return setStatusBarColor(activity, color, false);
  }

  /**
   * Set the status bar's color.
   *
   * @param activity The activity.
   * @param color    The status bar's color.
   * @param isDecor  True to add fake status bar in DecorView,
   *                 false to add fake status bar in ContentView.
   */
  public static View setStatusBarColor(@NonNull final AppCompatActivity activity,
                                       @ColorInt final int color,
                                       final boolean isDecor) {
    transparentStatusBar(activity);
    return applyStatusBarColor(activity, color, isDecor);
  }

  /**
   * Set the status bar's color.
   *
   * @param fakeStatusBar The fake status bar view.
   * @param color         The status bar's color.
   */
  public static void setStatusBarColor(@NonNull final View fakeStatusBar,
                                       @ColorInt final int color) {
    AppCompatActivity activity = getActivityByView(fakeStatusBar);
    if (activity == null) {
      return;
    }
    transparentStatusBar(activity);
    fakeStatusBar.setVisibility(View.VISIBLE);
    ViewGroup.LayoutParams layoutParams = fakeStatusBar.getLayoutParams();
    layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
    layoutParams.height = getStatusBarHeight();
    fakeStatusBar.setBackgroundColor(color);
  }

  /**
   * Set the custom status bar.
   *
   * @param fakeStatusBar The fake status bar view.
   */
  public static void setStatusBarCustom(@NonNull final View fakeStatusBar) {
    AppCompatActivity activity = getActivityByView(fakeStatusBar);
    if (activity == null) {
      return;
    }
    transparentStatusBar(activity);
    fakeStatusBar.setVisibility(View.VISIBLE);
    ViewGroup.LayoutParams layoutParams = fakeStatusBar.getLayoutParams();
    if (layoutParams == null) {
      layoutParams = new ViewGroup.LayoutParams(
              ViewGroup.LayoutParams.MATCH_PARENT,
              getStatusBarHeight()
      );
      fakeStatusBar.setLayoutParams(layoutParams);
    } else {
      layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
      layoutParams.height = getStatusBarHeight();
    }
  }

  /**
   * Set the status bar's color for DrawerLayout.
   * <p>DrawLayout must add {@code android:fitsSystemWindows="true"}</p>
   *
   * @param drawer        The DrawLayout.
   * @param fakeStatusBar The fake status bar view.
   * @param color         The status bar's color.
   */
  public static void setStatusBarColor4Drawer(@NonNull final DrawerLayout drawer,
                                              @NonNull final View fakeStatusBar,
                                              @ColorInt final int color) {
    setStatusBarColor4Drawer(drawer, fakeStatusBar, color, false);
  }

  /**
   * Set the status bar's color for DrawerLayout.
   * <p>DrawLayout must add {@code android:fitsSystemWindows="true"}</p>
   *
   * @param drawer        The DrawLayout.
   * @param fakeStatusBar The fake status bar view.
   * @param color         The status bar's color.
   * @param isTop         True to set DrawerLayout at the top layer, false otherwise.
   */
  public static void setStatusBarColor4Drawer(@NonNull final DrawerLayout drawer,
                                              @NonNull final View fakeStatusBar,
                                              @ColorInt final int color,
                                              final boolean isTop) {
    AppCompatActivity activity = getActivityByView(fakeStatusBar);
    if (activity == null) {
      return;
    }
    transparentStatusBar(activity);
    drawer.setFitsSystemWindows(false);
    setStatusBarColor(fakeStatusBar, color);
    for (int i = 0, count = drawer.getChildCount(); i < count; i++) {
      drawer.getChildAt(i).setFitsSystemWindows(false);
    }
    if (isTop) {
      hideStatusBarView(activity);
    } else {
      setStatusBarColor(activity, color, false);
    }
  }

  private static View applyStatusBarColor(final AppCompatActivity activity,
                                          final int color,
                                          boolean isDecor) {
    ViewGroup parent = isDecor ?
            (ViewGroup) activity.getWindow().getDecorView() :
            (ViewGroup) activity.findViewById(android.R.id.content);
    View fakeStatusBarView = parent.findViewWithTag(TAG_STATUS_BAR);
    if (fakeStatusBarView != null) {
      if (fakeStatusBarView.getVisibility() == View.GONE) {
        fakeStatusBarView.setVisibility(View.VISIBLE);
      }
      fakeStatusBarView.setBackgroundColor(color);
    } else {
      fakeStatusBarView = createStatusBarView(activity, color);
      parent.addView(fakeStatusBarView);
    }
    return fakeStatusBarView;
  }

  private static void hideStatusBarView(final AppCompatActivity activity) {
    hideStatusBarView(activity.getWindow());
  }

  private static void hideStatusBarView(final Window window) {
    ViewGroup decorView = (ViewGroup) window.getDecorView();
    View fakeStatusBarView = decorView.findViewWithTag(TAG_STATUS_BAR);
    if (fakeStatusBarView == null) {
      return;
    }
    fakeStatusBarView.setVisibility(View.GONE);
  }

  private static void showStatusBarView(final Window window) {
    ViewGroup decorView = (ViewGroup) window.getDecorView();
    View fakeStatusBarView = decorView.findViewWithTag(TAG_STATUS_BAR);
    if (fakeStatusBarView == null) {
      return;
    }
    fakeStatusBarView.setVisibility(View.VISIBLE);
  }

  private static View createStatusBarView(final AppCompatActivity activity,
                                          final int color) {
    View statusBarView = new View(activity);
    statusBarView.setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight()));
    statusBarView.setBackgroundColor(color);
    statusBarView.setTag(TAG_STATUS_BAR);
    return statusBarView;
  }

  private static void transparentStatusBar(final AppCompatActivity activity) {
    Window window = activity.getWindow();
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    int option = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
      int vis = window.getDecorView().getSystemUiVisibility() & View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
      window.getDecorView().setSystemUiVisibility(option | vis);
    } else {
      window.getDecorView().setSystemUiVisibility(option);
    }
    window.setStatusBarColor(Color.TRANSPARENT);
  }

  ///////////////////////////////////////////////////////////////////////////
  // action bar
  ///////////////////////////////////////////////////////////////////////////

  /**
   * Return the action bar's height.
   *
   * @return the action bar's height
   */
  public static int getActionBarHeight() {
    TypedValue tv = new TypedValue();
    if (BaseApplication.getInstance().getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
      return TypedValue.complexToDimensionPixelSize(
              tv.data, BaseApplication.getInstance().getResources().getDisplayMetrics()
      );
    }
    return 0;
  }

  ///////////////////////////////////////////////////////////////////////////
  // notification bar
  ///////////////////////////////////////////////////////////////////////////

  /**
   * Set the notification bar's visibility.
   * <p>Must hold {@code <uses-permission android:name="android.permission.EXPAND_STATUS_BAR" />}</p>
   *
   * @param isVisible True to set notification bar visible, false otherwise.
   */
  @RequiresPermission(EXPAND_STATUS_BAR)
  public static void setNotificationBarVisibility(final boolean isVisible) {
    String methodName;
    if (isVisible) {
      methodName = "expandNotificationsPanel";
    } else {
      methodName = "collapsePanels";
    }
    invokePanels(methodName);
  }

  private static void invokePanels(final String methodName) {
    try {
      @SuppressLint("WrongConstant")
      Object service =BaseApplication.getInstance().getSystemService("statusbar");
      @SuppressLint("PrivateApi")
      Class<?> statusBarManager = Class.forName("android.app.StatusBarManager");
      Method expand = statusBarManager.getMethod(methodName);
      expand.invoke(service);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  ///////////////////////////////////////////////////////////////////////////
  // navigation bar
  ///////////////////////////////////////////////////////////////////////////

  /**
   * Return the navigation bar's height.
   *
   * @return the navigation bar's height
   */
  public static int getNavBarHeight() {
    Resources res = Resources.getSystem();
    int resourceId = res.getIdentifier("navigation_bar_height", "dimen", "android");
    if (resourceId != 0) {
      return res.getDimensionPixelSize(resourceId);
    } else {
      return 0;
    }
  }

  /**
   * Set the navigation bar's visibility.
   *
   * @param activity  The activity.
   * @param isVisible True to set navigation bar visible, false otherwise.
   */
  public static void setNavBarVisibility(@NonNull final AppCompatActivity activity, boolean isVisible) {
    setNavBarVisibility(activity.getWindow(), isVisible);
  }

  /**
   * Set the navigation bar's visibility.
   *
   * @param window    The window.
   * @param isVisible True to set navigation bar visible, false otherwise.
   */
  public static void setNavBarVisibility(@NonNull final Window window, boolean isVisible) {
    final ViewGroup decorView = (ViewGroup) window.getDecorView();
    for (int i = 0, count = decorView.getChildCount(); i < count; i++) {
      final View child = decorView.getChildAt(i);
      final int id = child.getId();
      if (id != View.NO_ID) {
        String resourceEntryName = BaseApplication.getInstance()
                .getResources()
                .getResourceEntryName(id);
        if ("navigationBarBackground".equals(resourceEntryName)) {
          child.setVisibility(isVisible ? View.VISIBLE : View.INVISIBLE);
        }
      }
    }
    final int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
    if (isVisible) {
      decorView.setSystemUiVisibility(decorView.getSystemUiVisibility() & ~uiOptions);
    } else {
      decorView.setSystemUiVisibility(decorView.getSystemUiVisibility() | uiOptions);
    }
  }

  /**
   * Return whether the navigation bar visible.
   * <p>Call it in onWindowFocusChanged will get right result.</p>
   *
   * @param activity The activity.
   * @return {@code true}: yes<br>{@code false}: no
   */
  public static boolean isNavBarVisible(@NonNull final Activity activity) {
    return isNavBarVisible(activity.getWindow());
  }

  /**
   * Return whether the navigation bar visible.
   * <p>Call it in onWindowFocusChanged will get right result.</p>
   *
   * @param window The window.
   * @return {@code true}: yes<br>{@code false}: no
   */
  public static boolean isNavBarVisible(@NonNull final Window window) {
    boolean isVisible = false;
    ViewGroup decorView = (ViewGroup) window.getDecorView();
    for (int i = 0, count = decorView.getChildCount(); i < count; i++) {
      final View child = decorView.getChildAt(i);
      final int id = child.getId();
      if (id != View.NO_ID) {
        String resourceEntryName = BaseApplication.getInstance()
                .getResources()
                .getResourceEntryName(id);
        if ("navigationBarBackground".equals(resourceEntryName)
                && child.getVisibility() == View.VISIBLE) {
          isVisible = true;
          break;
        }
      }
    }
    if (isVisible) {
      int visibility = decorView.getSystemUiVisibility();
      isVisible = (visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0;
    }
    return isVisible;
  }

  /**
   * Set the navigation bar's color.
   *
   * @param activity The activity.
   * @param color    The navigation bar's color.
   */
  @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
  public static void setNavBarColor(@NonNull final AppCompatActivity activity, @ColorInt final int color) {
    setNavBarColor(activity.getWindow(), color);
  }

  /**
   * Set the navigation bar's color.
   *
   * @param window The window.
   * @param color  The navigation bar's color.
   */
  @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
  public static void setNavBarColor(@NonNull final Window window, @ColorInt final int color) {
    window.setNavigationBarColor(color);
  }

  /**
   * Return the color of navigation bar.
   *
   * @param activity The activity.
   * @return the color of navigation bar
   */
  @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
  public static int getNavBarColor(@NonNull final AppCompatActivity activity) {
    return getNavBarColor(activity.getWindow());
  }

  /**
   * Return the color of navigation bar.
   *
   * @param window The window.
   * @return the color of navigation bar
   */
  @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
  public static int getNavBarColor(@NonNull final Window window) {
    return window.getNavigationBarColor();
  }

  /**
   * Return whether the navigation bar visible.
   *
   * @return {@code true}: yes<br>{@code false}: no
   */
  public static boolean isSupportNavBar() {
    WindowManager wm = (WindowManager) BaseApplication.getInstance().getSystemService(Context.WINDOW_SERVICE);
    if (wm == null) {
      return false;
    }
    Display display = wm.getDefaultDisplay();
    Point size = new Point();
    Point realSize = new Point();
    display.getSize(size);
    display.getRealSize(realSize);
    return realSize.y != size.y || realSize.x != size.x;
  }

  private static AppCompatActivity getActivityByView(@NonNull final View view) {
    Context context = view.getContext();
    while (context instanceof ContextWrapper) {
      if (context instanceof AppCompatActivity) {
        return (AppCompatActivity) context;
      }
      context = ((ContextWrapper) context).getBaseContext();
    }
    Log.e("BarUtils", "the view's Context is not an Activity.");
    return null;
  }
}