Android沉浸式UI实现及原理

eegn6272 8年前
   <h2>沉浸式体验</h2>    <p>首先别吐槽<code>沉浸式</code>这个名词吧,毕竟这各名字是广为人知并且比<code>透明状态栏加透明导航栏</code>更酷。充分使用整个屏幕将这2个系统视图融入自己APP也算沉浸式体验吧。</p>    <p>首先2个名词:<br> <strong>StatusBar</strong>:</p>    <p><img src="https://simg.open-open.com/show/49b75b44a177694f2b01df616b82b50c.png" alt="Android沉浸式UI实现及原理" width="368" height="36"></p>    <p>Paste_Image.png</p>    <p><br> <strong>NavigationBar</strong>:</p>    <p><img src="https://simg.open-open.com/show/56b91bbc13acee34b4fe4d91eff65a07.png" alt="Android沉浸式UI实现及原理" width="382" height="61"></p>    <p>Paste_Image.png</p>    <p>下面是Google的官方标准模版:</p>    <p><img src="https://simg.open-open.com/show/326c8c2b77ac14db3f62d982d3dafd76.jpg" alt="Android沉浸式UI实现及原理" width="640" height="569"></p>    <p>未标题-1.jpg</p>    <p>在官方示例中:<br> StatusBar是一个半透明阴影,View可以伸展到其后面。<br> NavigationBar是纯黑不能使用的。</p>    <p>Google提供NavigationBar的透明与使用的可能,却没有推荐使用。个人觉得是为了给</p>    <p><img src="https://simg.open-open.com/show/cad677e1a7385d9e86d669abde717a61.png" alt="Android沉浸式UI实现及原理" width="363" height="106"></p>    <p>Paste_Image.png</p>    <p>Bottom navigation<br> 做准备。这里不讨论Bottom navigation的优劣(我是Bottom navigation黑)。</p>    <p>下面是B站的:</p>    <p><img src="https://simg.open-open.com/show/967968cd2851257f691ff09d54dc90bc.jpg" alt="Android沉浸式UI实现及原理" width="640" height="1138"></p>    <p>QQ图片20160525195336.jpg</p>    <p>不可否认使用NavigationBar空间对多下巴手机是种拯救。<br> (Google自己推的虚拟按键,却自己放弃了屏占比这一大优势。)</p>    <p>好了,B站的UI就是我所期望的UI。下面我们就来实现它。</p>    <h2>style的配置</h2>    <p>android从4.4开始,开始支持UI使用StatusBar与NavigationBar的范围。<br> 所以要进行下面的配置:</p>    <p>在value中的styles.xml中设置</p>    <pre>  <code class="language-java"><!-- Base application theme. -->  <style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">      <!-- Customize your theme here. -->  </style>  <style name="AppTheme" parent="AppTheme.Base"></style></code></pre>    <p>在value-v19中的styles.xml中设置(为了兼容4.4)</p>    <pre>  <code class="language-java"><style name="AppTheme" parent="AppTheme.Base">      <item name="android:windowTranslucentStatus">true</item>      <item name="android:windowTranslucentNavigation">true</item>  </style></code></pre>    <p>在value-v21中的styles.xml中设置</p>    <pre>  <code class="language-java"><style name="AppTheme" parent="AppTheme.Base">      <!--透明状态栏-->      <item name="android:windowTranslucentStatus">true</item>      <!--透明导航栏-->      <item name="android:windowTranslucentNavigation">true</item>       <!--使状态栏,导航栏可绘制-->      <item name="android:windowDrawsSystemBarBackgrounds">true</item>  </style></code></pre>    <p>然后使用AppTheme这个主题,这是1个示例,应该看得出来吧。只要在你的AppTheme的v19版本和v21版本添加了相应属性就好。</p>    <h2>使用ToolBar</h2>    <p>当你使用了StatusBar的部分,就不要再使用ActionBar了。<br> 现在基本都会使用ToolBar了吧。还不会可以参考 <a href="/misc/goto?guid=4959640207869059449">ToolBar的使用</a></p>    <p>然后效果如下:</p>    <p><img src="https://simg.open-open.com/show/dc2e91d8ada5273325ec0183a908eac9.jpg" alt="Android沉浸式UI实现及原理" width="640" height="1138"></p>    <p>QQ图片20160525195351.jpg</p>    <p>然后这里就有2个问题:</p>    <p><strong>1. Toolbar到了StatusBar的下面</strong>(为了凸显问题给Toolbar设了颜色)<br> <strong>2. View在NavigationBar下难以点击</strong></p>    <p>这2个问题也是理所应当就应该存在的。<br> <strong>解决方法</strong>:</p>    <h2>FitSystemWindowLayout</h2>    <p>这里就先说结果吧,使用<a href="/misc/goto?guid=4959673782555571097">FitSystemWindowLayout</a>,我为此做了很多适配工作。<br> 这是标准界面:</p>    <p><img src="https://simg.open-open.com/show/507d9b3109e98caeedd05024bbc36167.jpg" alt="Android沉浸式UI实现及原理" width="640" height="1138"></p>    <p>QQ图片20160525195401.jpg</p>    <p><br> 这个库提供自动适应StatusBar与NavigationBar的几个Layout。在XML中设置即可。<br> 这是上面标准UI的XML:</p>    <pre>  <code class="language-java"><?xml version="1.0" encoding="utf-8"?>  <com.jude.fitsystemwindowlayout.FitSystemWindowsFrameLayout      xmlns:android="http://schemas.android.com/apk/res/android"      xmlns:app="http://schemas.android.com/apk/res-auto"      xmlns:tools="http://schemas.android.com/tools"      android:layout_width="match_parent"      android:layout_height="match_parent"      app:padding_status="false"//不自动腾出StatusBar的空间,为了让图片在StatusBar下绘制      tools:context="com.jude.demo.MainActivity">        //这个ViewPager里面放的ImageView      <com.jude.rollviewpager.RollPagerView          android:id="@+id/viewpager"          android:layout_width="match_parent"          android:layout_height="300dp"          app:rollviewpager_play_delay="3000"/>        <android.support.v7.widget.Toolbar          android:id="@+id/toolbar"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:minHeight="?actionBarSize"          android:background="#0000"//透明ToolBar          app:theme="@style/AppTheme.Dark"          app:margin_status="true"//让ToolBar去适应StatusBar          />        <ScrollView          android:id="@+id/content"          android:layout_width="match_parent"          android:layout_height="match_parent"          app:padding_navigation="true"//只对可滑动View有效的属性,自动增加底部内Padding          android:layout_marginTop="300dp">          <TextView              android:layout_width="match_parent"              android:layout_height="wrap_content"              style="@style/Base.TextAppearance.AppCompat.Display3"              android:text="A\nB\nC\nD\nE\nF\nG"/>      </ScrollView>        <android.support.design.widget.FloatingActionButton          android:id="@+id/fab"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:layout_gravity="bottom|end"          android:layout_margin="@dimen/fab_margin"          app:margin_navigation="true"//让FAB去适应NavigationBar          android:src="@android:drawable/ic_dialog_email" />    </com.jude.fitsystemwindowlayout.FitSystemWindowsFrameLayout></code></pre>    <h2>FitSystemWindow的原理</h2>    <p>Android4.4与Android5.0的Insets处理机制完全不同。</p>    <p>Android 5.0的机制:</p>    <p>ViewRootImpl.java中掌管View绘制的函数。</p>    <pre>  <code class="language-java">private void performTraversals() {      ……      dispatchApplyInsets(host);      ……      performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);      ……      performLayout(lp, desiredWindowWidth, desiredWindowHeight);      ……      performDraw();  }    void dispatchApplyInsets(View host) {      host.dispatchApplyWindowInsets(getWindowInsets(true /* forceConstruct */));  }</code></pre>    <p>SystemBar的尺寸在WindowInsets 中表示出来,比如<code>Insets:(0, 63 , 0, 126)</code>。表示StatusBar高度63,NavigationBar高度126.<br> dispatchApplyWindowInsets 将WindowInsets 从View树顶部开始分发。</p>    <pre>  <code class="language-java">//View.java 代码经过精简  public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {      if (mListenerInfo != null && mListenerInfo.mOnApplyWindowInsetsListener != null) {          return mListenerInfo.mOnApplyWindowInsetsListener.onApplyWindowInsets(this, insets);      } else {          return onApplyWindowInsets(insets);      }  }  --------------------------------------------------------------------  //ViewGroup.java  @Override  public WindowInsets dispatchApplyWindowInsets(WindowInsets insets) {      insets = super.dispatchApplyWindowInsets(insets);      if (!insets.isConsumed()) {          final int count = getChildCount();          for (int i = 0; i < count; i++) {              insets = getChildAt(i).dispatchApplyWindowInsets(insets);              if (insets.isConsumed()) {                  break;              }          }      }      return insets;  }</code></pre>    <p>这个方法很简单。在View树中分发Insets,先序遍历。一旦被消费就终止分发。可以看到处理WindowInsets 主要是2个方式。</p>    <p>自定义Insets处理方式的方法1</p>    <p>给目标View注册监听<br> View接收到Insets。会先判断自己是否被注册了监听,监听是指这个,在这个监听里能够收到Insets。并依据自己情况处理。</p>    <pre>  <code class="language-java">public void setOnApplyWindowInsetsListener(OnApplyWindowInsetsListener listener) {      getListenerInfo().mOnApplyWindowInsetsListener = listener;  }</code></pre>    <p>自定义Insets处理方式的方法2</p>    <p>重写<code>onApplyWindowInsets</code><br> 先看看<strong>默认</strong>的实现。</p>    <pre>  <code class="language-java">//代码经过精简  public WindowInsets onApplyWindowInsets(WindowInsets insets) {      if (fitSystemWindowsInt(insets.getSystemWindowInsets())) {          //如果fitSystemWindowsInt返回true就消耗Instes,好简单的逻辑          return insets.consumeSystemWindowInsets();      }      return insets;  }</code></pre>    <p>重点来了<code>fitSystemWindowsInt</code>.它实质性的判断并设置了Padding。</p>    <pre>  <code class="language-java">private boolean fitSystemWindowsInt(Rect insets) {      //如果设置了FITS_SYSTEM_WINDOWS这个flag      if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {          mUserPaddingStart = UNDEFINED_PADDING;          mUserPaddingEnd = UNDEFINED_PADDING;          Rect localInsets = sThreadLocal.get();          if (localInsets == null) {              localInsets = new Rect();              sThreadLocal.set(localInsets);          }            //computeFitSystemWindows主要就是localInsets=insets。并清空insets          boolean res = computeFitSystemWindows(insets, localInsets);            mUserPaddingLeftInitial = localInsets.left;          mUserPaddingRightInitial = localInsets.right;            //直接应用这个Insets到padding          internalSetPadding(localInsets.left, localInsets.top,                  localInsets.right, localInsets.bottom);          return res;      }      return false;  }</code></pre>    <p>而<code>FITS_SYSTEM_WINDOWS</code>这个flag有2个来源:<br> 代码手动设置:</p>    <pre>  <code class="language-java">public void setFitsSystemWindows(boolean fitSystemWindows) {      setFlags(fitSystemWindows ? FITS_SYSTEM_WINDOWS : 0, FITS_SYSTEM_WINDOWS);  }</code></pre>    <p>在XML中设置<code>android:fitSystemWindow="true"</code>:</p>    <pre>  <code class="language-java"> case com.android.internal.R.styleable.View_fitsSystemWindows:       if (a.getBoolean(attr, false)) {           viewFlagValues |= FITS_SYSTEM_WINDOWS;           viewFlagMasks |= FITS_SYSTEM_WINDOWS;       }       break;</code></pre>    <p>这就很明显了。<br> 设置了<code>fitSystemWindow</code>,默认就会消费掉Insets,并设置padding。如果没有设置,会继续遍历直到被某个View消耗。</p>    <p>其实上面的代码是精简后的,实际上对4.4的机制做了一些兼容处理。为了便于理解删掉了。</p>    <p>Android 4.4的机制:</p>    <p>4.4的机制比5.0简单得多。</p>    <pre>  <code class="language-java">private void performTraversals() {      ……      host.fitSystemWindows(mFitSystemWindowsInsets);      ……      performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);      ……      performLayout(lp, desiredWindowWidth, desiredWindowHeight);      ……      performDraw();  }</code></pre>    <p>让DecorView执行<code>fitSystemWindows</code></p>    <pre>  <code class="language-java">//ViewGroup.java  @Override  protected boolean fitSystemWindows(Rect insets) {      boolean done = super.fitSystemWindows(insets);      if (!done) {          final int count = mChildrenCount;          final View[] children = mChildren;          for (int i = 0; i < count; i++) {              done = children[i].fitSystemWindows(insets);              if (done) {                  break;              }          }      }      return done;  }  ----------------------------------------------------  //View.java  //与5.0的fitSystemWindowsInt方法一样  protected boolean fitSystemWindows(Rect insets) {      if ((mViewFlags & FITS_SYSTEM_WINDOWS) == FITS_SYSTEM_WINDOWS) {          mUserPaddingStart = UNDEFINED_PADDING;          mUserPaddingEnd = UNDEFINED_PADDING;          Rect localInsets = sThreadLocal.get();          if (localInsets == null) {              localInsets = new Rect();              sThreadLocal.set(localInsets);          }          boolean res = computeFitSystemWindows(insets, localInsets);          mUserPaddingLeftInitial = localInsets.left;          mUserPaddingRightInitial = localInsets.right;          internalSetPadding(localInsets.left, localInsets.top,                  localInsets.right, localInsets.bottom);          return res;      }      return false;  }</code></pre>    <p>分发的过程变到了这里。并且直接就应用了。<br> 与5.0有很大不同(简单了好多)。<br> 重写<code>fitSystemWindows</code>方法即可实现与5.0一样的效果。</p>    <p><br>  </p>    <p>文/<a href="/misc/goto?guid=4959673782653469181">Jude95</a>(简书)<br>  </p>    <p> </p>