我有多个使用同一个容器的 fragment ,当一个 fragment 被添加到另一个 fragment 上时,我希望焦点只在最近添加的 fragment 中的 View 之间移动。我尝试使用 onBackstackChangeListener() 解决它,但它似乎不起作用。如图所示,我只想关注 Pin Entry fragment ,但焦点也转移到 Pin Entry fragment 后面的 fragment 上的“Enter”按钮。请帮忙。
最佳答案
我找到了解决此问题的方法,但这不是真正的解决方案,最佳答案将被标记为正确答案。
解决方法: 在您的布局周围添加需要焦点的 View 。例如:
<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:layout_gravity="center"
android:orientation="horizontal"/>
<View
android:layout_width="0dp"
android:layout_height="match_parent"
android:focusable="true"
android:id="@+id/left_view"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="@+id/buyOrWatch"
android:layout_width="90dp"
android:layout_height="30dp"
android:layout_margin="5dp"
android:background="@drawable/movie_buy_selector"
android:focusable="true"
android:gravity="center"
android:text="@string/buy"
android:textColor="@color/color_white" />
<TextView
android:id="@+id/preview"
android:layout_width="90dp"
android:layout_height="30dp"
android:layout_margin="5dp"
android:layout_marginTop="15dp"
android:background="@drawable/movie_buy_selector"
android:focusable="true"
android:gravity="center"
android:text="@string/preview"
android:textColor="@color/color_white" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="0dp"
android:focusable="true"
android:id="@+id/right_view"/>
我将带有 TextView 的布局放置在宽度为 0dp 的两个可聚焦 View 之间。
现在,在您的 fragment 类中,绑定(bind)那些 View ,然后为这些 View 定义一个 focusChangeListener()
。例如,如果 leftView
将 View 绑定(bind)到 id android:id="@+id/left_view"
并将 buyOrWatch
绑定(bind)到 TextView
拥有 android:id="@+id/buyOrWatch"
,然后,
leftView.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if(hasFocus){
buyOrWatch.requestFocus();
}
}
});
您可以像上面那样为每个 View 定义类似的焦点更改监听器,然后只要 fragment 可见,焦点就会留在 fragment 中。希望这对某人有帮助。
关于android - 将焦点限制在具有多个添加 fragment 的容器中的一个 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47504002/