FocusControl
焦点控制框架,用于Android TV应用的焦点控制。
在模块gradle目录下的dependencies闭包中添加如下代码即可集成焦点控制框架:
implementation 'io.github.BlueOcean1998:focuscontrol:1.0.0'
FocusControl集成了以下仓库:
api 'androidx.constraintlayout:constraintlayout:2.1.2'
api 'androidx.recyclerview:recyclerview:1.2.0'
FocusControl主要由FocusControlLinearLayout & FocusControlRelativeLayout
& FocusControlConstraintLayout & FocusControlRecyclerView组成。
它们都继承了FocusControlViewParent接口。
FocusControl提供了一系列焦点控制的方法,极大地方便了Android TV应用的焦点控制。
1.FocusControlLinearLayout;
(1).recordFocusEnabled & defFocusId & lastFocusView
在实际场景中,LinearLayout和RecyclerView经常需要记录焦点。
如:在一个页面中有2列子页面。左边一列是导航栏,有许多item,如果item很多还要求可以滚动,
右边一列根据左边选择的item切换对应页面,也有可能有需要item并需要滚动。
这样的页面通常需要使用LinearLayout+ScrollView & RecyclerView来写。
如果使用系统默认寻焦,从切到右时,右边的item就会因左边的item的位置不同而聚焦到不同的位置,
切回左边的item时也会因为右边的item的位置不同而聚焦到不同的位置,
而且会因切到左边的另一个item导致右边的页面发送变化。这是非常影响用户体验的。
FocusControlLinearLayout提供3个属性来解决上述场景中的问题
recordFocusEnabled:是否记录最后聚焦控件
若该属性为true,当焦点回到布局中时,会自动聚焦回布局之前最后聚焦的控件上。
defFocusId:默认聚焦控件id
其设置为布局的子控件id时,首次聚焦到布局中会自动聚焦到id指示的控件上。
lastFocusView:最后聚焦控件
当焦点在布局内发生变化时,lastFocusView会被设置为上一个聚焦的控件。
你可以在xml或代码中设置\获取它们。
示例代码:
xml:
<net.sunniwell.aar.focuscontrol.layout.FocusControlLinearLayout
android:id="@+id/fcl_root"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:defFocusId="@id/btn_1">
...
</net.sunniwell.aar.focuscontrol.layout.FocusControlLinearLayout>
kotlin:
viewBinding.run {
llRoot.recordFocusEnabled = false
llRoot.defFocusId = R.id.btn_1
llRoot.lastFocusView = btn1
val recordFocusEnabled = llRoot.recordFocusEnabled
val defFocusId = llRoot.defFocusId
val lastFocusView = llRoot.lastFocusView