作者地址http://www.jianshu.com/u/63915ef020e2

针对Android Tv的自定义RecyclerView

作者 wenju_song 关注

2016.12.09 19:52* 字数 814 阅读 1368评论 17喜欢 22

前言:Android TV Launcher页在RecyclerView出来之前大家用GridView去实现。TV开发有五向键的监听,遥控器hover监听,点击事件等。用GridView去处理焦点是有一定挑战性的,往往会出现不可预料焦点错乱问题。这里封装了一个针对TV的RecyclerView,很方便的处理了这些事件。

首先上效果图:

tvRecycler.gif

这里封装了RecyclerView实现了下面的一些功能:
1.响应五向键,按下五向键的上下左右会跟着移动,并获得焦点,在获得焦点时会抬高。
2.在鼠标hover在条目上时会获得焦点。
3.添加了条目的点击和长按事件。
4.添加了是否第一个可见条目和是否是最后一个可见条目的方法。
5.在item获得焦点时和失去焦点时,这里有相应的回调方法。

实现

下面分析一些关键的点:
1.鼠标滑动时避免跟着滑动,只响应五向键和左右箭头

   @Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//在recyclerView的move事件情况下,拦截调,只让它响应五向键和左右箭头移动
LogUtil.i(this, "CustomRecycleView.dispatchTouchEvent.");
return ev.getAction() == MotionEvent.ACTION_MOVE || super.dispatchTouchEvent(ev);
}

2.使用StaggeredGridLayoutManager实现管理,如果使用GridLayoutManager会出现焦点的错乱,当使用五向键左右移动时,会从上面转移到下面。原因是GridLayoutManager会存在分组。

//设置布局管理器
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.HORIZONTAL);
mRecyclerView.setLayoutManager(layoutManager);

3.设置RecyclerView的item有焦点。按五向键,焦点会跟着一起移动

holder.itemView.setFocusable(true);

4,左右键,让RecyclerView跟着一起滚动,并获得焦点:

 @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;
}

这里请求获取焦点的方法是:

rightView.requestFocusFromTouch();

TV的焦点的处理的逻辑比较复杂:

可以参考这篇文章:http://www.cnblogs.com/myzh/p/3664544.html

5.在holder里监听到焦点变化时做一些处理:

    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);

这里抽象了两个方法,当item获得焦点和失去焦点时调用。获得焦点时条目会抬高,这里是抬高了Z轴。

6.获取在第一个和最后一个可见的条目,根据这些状态去显示和隐藏左右箭头。

   /**
* 第一个条目是否可见
*
* @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;
}

下面说一个坑,在处理最后一个条目时可见时,我发现拿到的数据并不是一种情况,当一共有三行时。

用下面的代码来打出位置:

for (int i = 0; i < lastVisibleItems.length; i++) {
LogUtil.i(this, "order:"+i +"----->last position:" + lastVisibleItems[i]);
}

有三种情况:

1.最后一列只有有一个时,打出的log是

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

2.当最后一列有两个时:

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

3.当最后一行有三个时:

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

所以这里的处理是传入行数:

boolean isVisible = position >= (allItemNum - lineNum);来判断是否可见。

7.在Recycler滚动时候去处理箭头的显示状态:

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();
}
}

结束:

注意在使用该控件时,要设置RecyclerView的宽度是Item的整数倍,左右箭头点击滑动的距离也要设置为RecyclerView宽度。
项目的地址:https://github.com/songwenju/CustomTvRecyclerView
如果对你有帮助,欢迎star和fork。

Android为TV端助力(转载)的更多相关文章

  1. Android为TV端助力 转载:RecyclerView分页加载

    package com.android.ryane.pulltoloaddata_recyclerview; import android.os.Handler;import android.os.L ...

  2. Android为TV端助力:(转载)修改TextView字体样式

    一.开篇 因为 Android 字体相关的内容还比较多的.有时候其实我们只需要调整一下属性就可以满足设计师的需求,或者是一个退后的方案(毕竟有发版的时间卡住了),有一些效果可以大概满足需求. 那么本文 ...

  3. Android为TV端助力转载:码农小阿飞(SpannableString)

    用SpannableString打造绚丽多彩的文本显示效果 引语 TeXtView大家应该都不陌生,文本展示控件嘛! 就用TextView显示普普通通的文本,OK,很简单,Android入门的都会,没 ...

  4. Android为TV端助力 转载:android MVC设计模式

    Controller控制器 import android.app.Dialog; import android.app.ProgressDialog; import android.os.Bundle ...

  5. Android为TV端助力 转载:Android绘图Canvas十八般武器之Shader详解及实战篇(上)

    前言 Android中绘图离不开的就是Canvas了,Canvas是一个庞大的知识体系,有Java层的,也有jni层深入到Framework.Canvas有许多的知识内容,构建了一个武器库一般,所谓十 ...

  6. Android为TV端助力 转载:Android绘图Canvas十八般武器之Shader详解及实战篇(下)

    LinearGradient 线性渐变渲染器 LinearGradient中文翻译过来就是线性渐变的意思.线性渐变通俗来讲就是给起点设置一个颜色值如#faf84d,终点设置一个颜色值如#CC423C, ...

  7. Android为TV端助力 转载:android自定义view实战(温度控制表)!

    效果图 package cn.ljuns.temperature.view; import com.example.mvp.R; import android.content.Context;impo ...

  8. Android为TV端助力 转载自jguangyou的博客,XML基本属性大全

    android:layout_width 指定组件布局宽度 android:layout_height 指定组件布局高度 android:alpha 设置组件透明度 android:backgroun ...

  9. Android为TV端助力 转载弩的博客

    Android.mk简介:Android.mk文件用来告知NDK Build 系统关于Source的信息. Android.mk将是GNU Makefile的一部分,且将被Build System解析 ...

  10. Android为TV端助力 转载:Java 泛型

    一. 泛型概念的提出(为什么需要泛型)? 首先,我们看下下面这段简短的代码: 1 public class GenericTest { 2 3 public static void main(Stri ...

随机推荐

  1. [Swift]LeetCode110. 平衡二叉树 | Balanced Binary Tree

    Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary ...

  2. python之PIL库(Image模块)

    PIL(Python Image Library)是python的第三方图像处理库,PIL的功能非常的强大,几乎被认定是Python的官方图像处理库了. 由于PIL仅支持到python2.7于是一群志 ...

  3. beoplay(BO)耳机拒绝配对的解决方法

    最近买了个beoplay h4,但是在换了手机之后怎么也不能配对,问客服也不知道,后来找了好久才找到答案: 按住音量+  和 音量-  指示灯出现蓝色并闪烁时,手机搜索蓝牙就可以连接了

  4. 3.django Model

    django ORM基本配置 django中遵循 Code Frist 的原则,即:根据代码中定义的类来自动生成数据库表 1.修改project数据库配置 (1)settigs.py里面 默认 DAT ...

  5. ImportError: cannot import name UnrewindableBodyError

    错误信息: File "/usr/lib/python2.7/site-packages/urllib3/util/__init__.py", line 4, in <mod ...

  6. Chapter 5 Blood Type——27

    And then Mike staggered through the door, now supporting a sallow-looking Lee Stephens, another boy ...

  7. 补习系列(6)- springboot 整合 shiro 一指禅

    目标 了解ApacheShiro是什么,能做什么: 通过QuickStart 代码领会 Shiro的关键概念: 能基于SpringBoot 整合Shiro 实现URL安全访问: 掌握基于注解的方法,以 ...

  8. JS引擎线程的执行过程的三个阶段(一)

    浏览器首先按顺序加载由<script>标签分割的js代码块,加载js代码块完毕后,立刻进入以下三个阶段,然后再按顺序查找下一个代码块,再继续执行以下三个阶段,无论是外部脚本文件(不异步加载 ...

  9. C语言之递归

    递归例子如下: #include <stdio.h> /*函数声明*/ void digui(int n); int main() { ; digui(n); ; } void digui ...

  10. Linux基础命令第三天

    1,vim编辑器 命令模式下: pageup 往上翻页 pagedown 往下翻页 H 光标移动到屏幕首行 gg 光标动荡到文档的首行,如果前面加上n,表示移动到n行 G 移动文档最后一行 /name ...