背景
最近在学习如何按照自己的需求改变焦点的位置,记录学习中遇到的api
简单的焦点切换
看一个简单的需求。看图。
这样并排的多个功能的入口,假如是固定了,但是根据就近原则,大米的向下↓是走end的,这里我们不走系统推荐的,我们更改为第二行的第一个元素。
先看看默认:
更改↓的逻辑之后的:
使用nextFocus方法强制聚焦
nextFocus方法可以在代码做也可以在xml布局中配置。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".demo01.DemoFocusActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="@drawable/btn_selector"
android:text="小米" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="@drawable/btn_selector"
android:text="苹果" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="@drawable/btn_selector"
android:nextFocusRight="@null"
android:nextFocusDown="@id/btn_zimi"
android:text="大米" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/btn_zimi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="@drawable/btn_selector"
android:text="紫米" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="@drawable/btn_selector"
android:text="雪梨" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="@drawable/btn_selector"
android:text="end" />
</LinearLayout>
</LinearLayout>
我们在xml中指定down方向的聚焦控件的id就行
android:nextFocusRight="@null"
android:nextFocusDown="@id/btn_zimi"
当设置null的时候在该方向键操作响应就是不做事,会卡在当前控件上面。
简单的强制切换焦点就是这样了。
nextFocusRight
nextFocusDown
nextFocusUp
nextFocusLeft
项目地址 https://gitee.com/dong_rong/android-tv-sample