我正在使用 Android Leanback 库来创建电视应用程序。我有一个扩展 Fragment (即 RowsSupportFragment)的布局,其下方有一个按钮。因此,当我在到达最后一个项目后向下滚动到 RowsSupportFragment 中的项目列表时,焦点不会转到按钮。 我已经尝试过设置 focusable(true), nextFocusDown(buttonId) 等
我可以看到 RowsSupportFragment 在内部使用 VerticalGridView 来膨胀项目列表。
有人对此有任何想法吗?
这是我的布局:
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<FrameLayout
android:id="@+id/listviewFragmentId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:duplicateParentState="true"
android:nextFocusDown="@id/nextButtonId"
android:nextFocusForward="@id/nextButtonId"
layout_constraintBottom_toTopOf="@id/nextButtonId"/>
<Button
android:id="@+id/nextButtonId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:duplicateParentState="true"
android:focusable="true"
android:text="Hello Next"/>
<// other items>
</android.support.constraint.ConstraintLayout>
注意: 如果我左/右对齐按钮,焦点可以正常工作。
就我而言,当我需要关注任何视图时,这是工作
view.requestFocus();
在我的例子中,我需要关注 RowSupportFragment 项目之外的任何视图,因此使用 focusOutEnd、focusOutFront 和 Leanback 样式中的其他焦点功能解决了我的解决方案。 就像从 RowSupportFragment 请求焦点到外部 Button 小部件一样,设置
<item name="focusOutEnd">true</item>
的样式对我有用。
您可以按照以下步骤继续操作。
第1步: 当用户按遥控器上的后退按钮时显示菜单或选择其他视图。然后请求菜单列表中第一项的焦点。
@Override
public void onBackPressed() {
if(binding.llMenu.getVisibility() == View.VISIBLE){
super.onBackPressed();
}else {
binding.llMenu.setVisibility(View.VISIBLE);
binding.tvM1.requestFocus();
}
}
第2步: 您必须覆盖这些视图或菜单的点击侦听器。
binding.tvM2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// your code
Log.e("selected", "m2");
}
});
binding.tvM2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// your code
Log.e("selected", "m2");
}
});
第3步: 您可以在焦点更改侦听器上显示一些选择效果。
@Override
public void onFocusChange(View view, boolean b) {
if(b){
view.startAnimation(AnimationUtils.loadAnimation(view.getContext(), R.anim.zoom_in));
}else{
view.startAnimation(AnimationUtils.loadAnimation(view.getContext(), R.anim.zoom_out));
}
}
现在您的遥控器(d-pad)将按预期工作。当用户按下后退按钮时,它将强制聚焦于菜单,如果用户再次按下后退按钮,它将退出应用程序。