针对Android Tv的自定义RecyclerView

2248831048 8年前
   <p>前言:Android TV Launcher页在RecyclerView出来之前大家用GridView去实现。TV开发有五向键的监听,遥控器hover监听,点击事件等。用GridView去处理焦点是有一定挑战性的,往往会出现不可预料焦点错乱问题。这里封装了一个针对TV的RecyclerView,很方便的处理了这些事件。</p>    <p>下面是效果图:</p>    <p><img src="https://simg.open-open.com/show/e5c6499187646c73d70836c4b1bea1d0.gif"></p>    <p>封装了RecyclerView实现了一下一些功能:</p>    <p>1.响应五向键,按下五向键的上下左右会跟着移动,并获得焦点,在获得焦点时会抬高</p>    <p>2.在鼠标hover在条目上时会获得焦点。</p>    <p>3.添加了条目的点击和长按事件。</p>    <p>4.添加了是否第一个可见条目和是否是最后一个可见条目的方法。</p>    <p>5.在item获得焦点时和失去焦点时,这里有相应的回调方法。</p>    <p>下面分析一下一些关键的点:</p>    <p>1.鼠标滑动时避免跟着滑动,只响应五向键和左右箭头</p>    <pre>  <code class="language-java">@Override      public boolean dispatchTouchEvent(MotionEvent ev) {          //在recyclerView的move事件情况下,拦截调,只让它响应五向键和左右箭头移动          LogUtil.i(this, "CustomRecycleView.dispatchTouchEvent.");          return ev.getAction() == MotionEvent.ACTION_MOVE || super.dispatchTouchEvent(ev);      }</code></pre>    <p>2.使用StaggeredGridLayoutManager实现管理,如果使用GridLayoutManager会出现焦点的错乱,当使用五向键左右移动时,会从上面转移到下面。原因是GridLayoutManager会存在分组。</p>    <pre>  <code class="language-java">//设置布局管理器  StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.HORIZONTAL);  mRecyclerView.setLayoutManager(layoutManager);</code></pre>    <p>3.设置RecyclerView的item有焦点。按五向键,焦点会跟着一起移动</p>    <pre>  <code class="language-java">holder.itemView.setFocusable(true);</code></pre>    <p>4,左右键,让RecyclerView跟着一起滚动,并获得焦点:</p>    <pre>  <code class="language-java">@Override      public boolean dispatchKeyEvent(KeyEvent event) {          boolean result = super.dispatchKeyEvent(event);          int dx = this.getChildAt(0).getWidth();          View focusView = this.getFocusedChild();          if (focusView != null) {              switch (event.getKeyCode()) {                  case KeyEvent.KEYCODE_DPAD_RIGHT:                      if (event.getAction() == KeyEvent.ACTION_UP) {                          return true;                      } else {                          View rightView = FocusFinder.getInstance().findNextFocus(this, focusView, View.FOCUS_RIGHT);                          LogUtil.i(this, "rightView is null:" + (rightView == null));                          if (rightView != null) {                              rightView.requestFocusFromTouch();                              return true;                          } else {                              this.smoothScrollBy(dx, 0);                              return true;                          }                      }                  case KeyEvent.KEYCODE_DPAD_LEFT:                      View leftView = FocusFinder.getInstance().findNextFocus(this, focusView, View.FOCUS_LEFT);                      LogUtil.i(this, "left is null:" + (leftView == null));                      if (event.getAction() == KeyEvent.ACTION_UP) {                          return true;                      } else {                          if (leftView != null) {                              leftView.requestFocusFromTouch();                              return true;                          } else {                              this.smoothScrollBy(-dx, 0);                              return true;                          }                      }              }          }          return result;      }</code></pre>    <p>这里请求获取焦点的方法是:</p>    <pre>  <code class="language-java">rightView.requestFocusFromTouch();</code></pre>    <p>TV的焦点的处理的逻辑比较复杂:</p>    <p>可以参考这篇文章: <a href="/misc/goto?guid=4959728742025965967" rel="nofollow,noindex">http://www.cnblogs.com/myzh/p/3664544.html</a></p>    <p>5.在holder里监听到焦点变化时做一些处理:</p>    <pre>  <code class="language-java">holder.itemView.setOnFocusChangeListener(new View.OnFocusChangeListener() {                  @Override                  public void onFocusChange(View v, boolean hasFocus) {                      if (hasFocus) {                          focusStatus(v);                      } else {                          normalStatus(v);                      }                  }              });          /**           * item获得焦点时调用           *           * @param itemView view           */          private void focusStatus(View itemView) {              if (itemView == null) {                  return;              }              if (Build.VERSION.SDK_INT >= 21) {                  //抬高Z轴                  ViewCompat.animate(itemView).scaleX(1.10f).scaleY(1.10f).translationZ(1).start();              } else {                  ViewCompat.animate(itemView).scaleX(1.10f).scaleY(1.10f).start();                  ViewGroup parent = (ViewGroup) itemView.getParent();                  parent.requestLayout();                  parent.invalidate();              }              onItemFocus(itemView);          }          /**           * 当item获得焦点时处理           *           * @param itemView itemView           */          protected abstract void onItemFocus(View itemView);          /**           * item失去焦点时           *           * @param itemView item对应的View           */          private void normalStatus(View itemView) {              if (itemView == null) {                  return;              }              if (Build.VERSION.SDK_INT >= 21) {                  ViewCompat.animate(itemView).scaleX(1.0f).scaleY(1.0f).translationZ(0).start();              } else {                  ViewCompat.animate(itemView).scaleX(1.0f).scaleY(1.0f).start();                  ViewGroup parent = (ViewGroup) itemView.getParent();                  parent.requestLayout();                  parent.invalidate();              }              onItemGetNormal(itemView);          }          /**           * 当条目失去焦点时调用           *           * @param itemView 条目对应的View           */          protected abstract void onItemGetNormal(View itemView);</code></pre>    <p>这里抽象了两个方法,当item获得焦点和失去焦点时调用。获得焦点时条目会抬高,这里是抬高了Z轴。</p>    <p>6.获取在第一个和最后一个可见的条目,根据这些状态去显示和隐藏左右箭头。</p>    <pre>  <code class="language-java">/**       * 第一个条目是否可见       *       * @return 可见返回true,不可见返回false       */      public boolean isFirstItemVisible() {          LayoutManager layoutManager = getLayoutManager();          if (layoutManager instanceof StaggeredGridLayoutManager) {              int[] firstVisibleItems = null;              firstVisibleItems = ((StaggeredGridLayoutManager) layoutManager).                      findFirstCompletelyVisibleItemPositions(firstVisibleItems);              int position = firstVisibleItems[0];              return position == 0;          } else if (layoutManager instanceof LinearLayoutManager) {              int position = ((LinearLayoutManager) layoutManager).findFirstCompletelyVisibleItemPosition();              return position == 0;          }          return false;      }      /**       * 最后一个条目是否可见       *       * @param lineNum    行数       * @param allItemNum item总数       * @return 可见返回true,不可见返回false       */      public boolean isLastItemVisible(int lineNum, int allItemNum) {          LayoutManager layoutManager = getLayoutManager();          if (layoutManager instanceof StaggeredGridLayoutManager) {              int[] lastVisibleItems = null;              lastVisibleItems = ((StaggeredGridLayoutManager) layoutManager).findLastCompletelyVisibleItemPositions(lastVisibleItems);              int position = lastVisibleItems[0];              LogUtil.i(this, "lastVisiblePosition:" + position);              boolean isVisible = position >= (allItemNum - lineNum);              if (isVisible) {                  scrollBy(1, 0);              }              return isVisible;          } else if (layoutManager instanceof LinearLayoutManager) {              int position = ((LinearLayoutManager) layoutManager).findLastCompletelyVisibleItemPosition();              return position == allItemNum - 1;          }          return false;      }</code></pre>    <p>下面说一个坑,在处理最后一个条目时可见时,我发现拿到的数据并不是一种情况,当一共有三行时。</p>    <p>用下面的代码来打出位置:</p>    <pre>  <code class="language-java">for (int i = 0; i < lastVisibleItems.length; i++) {                  LogUtil.i(this, "order:"+i +"----->last position:" + lastVisibleItems[i]);  }</code></pre>    <p>有三种情况:</p>    <p>1.最后一列只有有一个时,打出的log是</p>    <pre>  <code class="language-java">01-06 02:40:51.868 4135-4135/com.songwenju.customtvrecyclerview I/swjCustomRecyclerView: order:0----->last position:12  01-06 02:40:51.869 4135-4135/com.songwenju.customtvrecyclerview I/swjCustomRecyclerView: order:1----->last position:10  01-06 02:40:51.869 4135-4135/com.songwenju.customtvrecyclerview I/swjCustomRecyclerView: order:2----->last position:11</code></pre>    <p>2.当最后一列有两个时:</p>    <pre>  <code class="language-java">01-06 02:41:54.285 6109-6109/com.songwenju.customtvrecyclerview I/swjCustomRecyclerView: order:0----->last position:12  01-06 02:41:54.286 6109-6109/com.songwenju.customtvrecyclerview I/swjCustomRecyclerView: order:1----->last position:13  01-06 02:41:54.286 6109-6109/com.songwenju.customtvrecyclerview I/swjCustomRecyclerView: order:2----->last position:11</code></pre>    <p>3.当最后一行有三个时:</p>    <pre>  <code class="language-java">01-06 02:43:21.336 8818-8818/com.songwenju.customtvrecyclerview I/swjCustomRecyclerView: order:0----->last position:12  01-06 02:43:21.337 8818-8818/com.songwenju.customtvrecyclerview I/swjCustomRecyclerView: order:1----->last position:13  01-06 02:43:21.337 8818-8818/com.songwenju.customtvrecyclerview I/swjCustomRecyclerView: order:2----->last position:14</code></pre>    <p>所以这里的处理是传入行数:</p>    <pre>  <code class="language-java">boolean isVisible = position >= (allItemNum - lineNum);来判断是否可见。</code></pre>    <p>7.在Recycler滚动时候去处理箭头的显示状态:</p>    <pre>  <code class="language-java">private class MyOnScrollListener extends RecyclerView.OnScrollListener {          @Override          public void onScrollStateChanged(RecyclerView recyclerView, int newState) {              super.onScrollStateChanged(recyclerView, newState);          }          @Override          public void onScrolled(RecyclerView recyclerView, int dx, int dy) {              super.onScrolled(recyclerView, dx, dy);              //在滚动的时候处理箭头的状态              setLeftArrStatus();              setRightArrStatus();          }      }</code></pre>    <p>来自:http://www.jianshu.com/p/566bd6188f4d</p>    <p> </p>