在 Android 上设置包装组件的焦点顺序



我在使用自定义组件时无法控制焦点顺序。具体来说,当我用不可聚焦的组件包装一个 EditText 然后将两个放在水平的 LinearLayout 中时,只有第一个会获得焦点。(我在上面添加了其他功能;下面的代码是 MRE。

我尝试使用nextFocusForward和nextFocusDown来设置焦点顺序,我已经确认它在原始EditTexts上正确工作,但在自定义视图上没有。我还尝试将该属性传递给 EditText,但这也没有用。我也尝试使我的自定义视图可聚焦,但它没有收到焦点事件(我认为是因为 EditText 接收它们(并且有同样的问题。

edittext_wrapper.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
tools:text="test"
/>
</LinearLayout>

EditTextWrapper.java:

public class EditTextWrapper extends LinearLayout {
public EditTextWrapper(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.edittext_wrapper, this, true);
}
}

activity_test.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<com.....EditTextWrapper
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<com.....EditTextWrapper
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:nextFocusDown="@id/right"
/>
<com.....EditTextWrapper
android:id="@+id/right"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
</LinearLayout>
<com.....EditTextWrapper
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>

我期待当光标位于第二个 EditText 中并且您按键盘上的下一个键时,它会转到第三个,但它会转到第 4 个。

我怀疑手动设置 nextFocusDown 的 id 不起作用的原因是因为我使用的是无法聚焦的包装类的 ID。我不确定接下来应该尝试什么。

我已经检查过更改您的编辑文本包装器.xml文件

<?xml version="1.0" encoding="utf-8"?>

<EditText
android:id="@+id/label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/app_name"
android:imeOptions="actionNext"
android:inputType="textEmailAddress"
tools:text="test" />

您也可以将其用于焦点小部件

view.requestFocus();

最新更新