下一步专注于RecyclerView内的自定义视图

4

我有一个RecyclerView用于表示表单。这些RecyclerView由多种类型的View组成。每个View都有一个base_layout和特定的View,具体取决于它们所代表的数据类型(例如:字符串将由EditText表示)。

以下是表示string数据类型的布局文件:

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <include android:id="@+id/base_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        layout="@layout/view_form_field_base"
        app:label="@{viewModel.label}"
        app:errorMessage="@{viewModel.formElement.errorMessage}"
        app:canGenerate="@{viewModel.formElement.canBeGenerated &amp;&amp; viewModel.editable}" />

    <com.my.app.views.edittext.ActionEditText
        android:id="@+id/field_content"
        android:layout_width="0dp"
        android:layout_height="wrap_content"

        android:layout_marginEnd="8dp"
        android:padding="@{viewModel.editable ? 10 : 0}"

        android:background="@{viewModel.editable ? @drawable/my_edit_text_background : @drawable/empty_drawable}"

        android:clickable="@{viewModel.editable}"
        android:cursorVisible="@{viewModel.editable}"
        android:focusableInTouchMode="@{viewModel.editable}"
        android:focusable="@{viewModel.editable}"
        android:inputType="textMultiLine|textNoSuggestions"

        android:ellipsize="end"
        android:text="@={viewModel.formElement.value}"
        app:layout_constraintBottom_toTopOf="@+id/error_message"
        app:layout_constraintEnd_toStartOf="@+id/generate_button"
        app:layout_constraintStart_toStartOf="@+id/label"
        app:layout_constraintTop_toBottomOf="@+id/label" />

</android.support.constraint.ConstraintLayout>

当一个表单仅由字符串组成时,没有问题。但也有一些自定义视图。例如:

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <include android:id="@+id/base_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        layout="@layout/view_form_field_base"
        app:label="@{viewModel.label}"
        app:errorMessage="@{viewModel.formElement.errorMessage}"/>

    <com.my.app.views.dynamic_list.DynamicRadioGroup
        android:id="@+id/field_content"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="@+id/label"
        app:layout_constraintEnd_toStartOf="@+id/medical_record_level"
        app:layout_constraintBottom_toTopOf="@+id/error_message"
        app:layout_constraintTop_toBottomOf="@+id/label"

        app:setEditable="@{viewModel.editable}"
        android:layout_marginEnd="8dp" />

</android.support.constraint.ConstraintLayout>

当像上面那样的自定义类型字段前面是字符串类型时,当我们在聚焦字符串类型字段并点击键盘的“下一个”按钮时,应用程序会崩溃。
崩溃堆栈跟踪:
java.lang.IllegalStateException: focus search returned a view that wasn't able to take focus!
        at android.widget.TextView.onKeyUp(TextView.java:7520)
        at android.view.KeyEvent.dispatch(KeyEvent.java:3361)
        at android.view.View.dispatchKeyEvent(View.java:10615)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1697)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1697)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1697)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1697)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1697)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1697)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1697)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1697)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1697)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1697)
        at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1697)
        at com.android.internal.policy.DecorView.superDispatchKeyEvent(DecorView.java:590)
        at com.android.internal.policy.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1885)
        at android.support.v4.view.KeyEventDispatcher.activitySuperDispatchKeyEventPre28(KeyEventDispatcher.java:130)
        at android.support.v4.view.KeyEventDispatcher.dispatchKeyEvent(KeyEventDispatcher.java:87)
        at android.support.v4.app.SupportActivity.dispatchKeyEvent(ComponentActivity.java:126)
        at android.support.v7.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:535)
        at com.pascalwelsch.compositeandroid.activity.CompositeActivity.super_dispatchKeyEvent(CompositeActivity.java:2264)
        at com.pascalwelsch.compositeandroid.activity.ActivityDelegate.dispatchKeyEvent(ActivityDelegate.java:756)
        at com.pascalwelsch.compositeandroid.activity.CompositeActivity.dispatchKeyEvent(CompositeActivity.java:278)
        at android.support.v7.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:59)
        at android.support.v7.app.AppCompatDelegateImpl$AppCompatWindowCallback.dispatchKeyEvent(AppCompatDelegateImpl.java:2533)
        at android.support.v7.view.WindowCallbackWrapper.dispatchKeyEvent(WindowCallbackWrapper.java:59)
        at com.android.internal.policy.DecorView.dispatchKeyEvent(DecorView.java:467)
        at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:5041)
        at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:5003)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4532)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4585)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4551)
        at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4684)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4559)
        at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4741)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4532)
        at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4585)
        at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4551)
        at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4559)
        at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4532)
        at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:7092)
        at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:7024)
        at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6985)
        at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:4181)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6776)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)

最后,这里是DynamicRadioGroup的Java类:

public class DynamicRadioGroup extends ViewSwitcher {
    private CharSequence[] values;
    private int defaultValuePosition;
    private int orientation;
    private String selectedValue;
    private RadioGroup radioGroup;
    private TextView checkedOption;
    private OnValueChangeListener listener;

    public DynamicRadioGroup(Context context) {
        super(context);
        init();
    }

    /**
     * Initialize the view.
     */
    private void init() {
        //The ViewSwitcher will wrap its currently displayed layout.
        this.setMeasureAllChildren(false);

        //Tried this to fix the issue.
        this.setDescendantFocusability(FOCUS_BEFORE_DESCENDANTS);

        radioGroup = new RadioGroup(getContext());
        checkedOption = new TextView(getContext(), null, dynamicRadioGroupStyle);
        checkedOption.setGravity(Gravity.CENTER_VERTICAL);
        radioGroup.setOrientation(orientation);

        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            RadioButton radioButton = group.findViewById(checkedId);
            if (radioButton != null) {
                selectedValue = radioButton.getText().toString();
                checkedOption.setText(selectedValue);
                if (listener != null)
                    listener.onValuesChanged(this, selectedValue, checkedId);
            }
        });

        addView(radioGroup, 0);
        addView(checkedOption, 1);
    }

    //region GETTER & SETTER
    public void setValues(CharSequence[] values) {
        this.values = values;
        if(CollectionUtils.isNullOrEmpty(values)
            return;
        radioGroup.removeAllViews();
        for (int i = 0; i < this.values.length; i++) {
            RadioButton radioButton = new RadioButton(getContext());
            radioButton.setText(this.values[i]);
            radioButton.setId(i);
            if (radioGroup.getOrientation() == LinearLayout.HORIZONTAL)
                radioButton.setLayoutParams(new RadioGroup.LayoutParams(0, RadioGroup.LayoutParams.WRAP_CONTENT, 1.0f));
            radioGroup.addView(radioButton);
        }

    }

    public void setDefaultValuePosition(int defaultValuePosition) {
        this.defaultValuePosition = defaultValuePosition;
        RadioButton radioButton = (RadioButton) radioGroup.getChildAt(this.defaultValuePosition);
        if (radioButton != null) {
            radioGroup.clearCheck();
            radioButton.setChecked(true);
        }
    }

    public void setEditable(boolean editable) {
        setDisplayedChild(editable ? 0 : 1);
        setFocusable(editable);
    }

    public String getSelectedValue() {
        return selectedValue;
    }

    public void setSelectedValue(String selectedValue) {
        this.selectedValue = selectedValue;
    }

    public int getOrientation() {
        return orientation;
    }

    public void setOrientation(int orientation) {
        this.orientation = orientation;
        if (radioGroup != null)
            radioGroup.setOrientation(orientation);
    }

    public void setOnValueChangeListener(OnValueChangeListener listener) {
        this.listener = listener;
    }

    @Override
    protected boolean onRequestFocusInDescendants(final int dir, final Rect rect) {
        final View view = radioGroup.findViewById(radioGroup.getCheckedRadioButtonId());
        return view.requestFocus();
    }
    //endregion

}

我们可以看到,我尝试使用setDescendantFocusability方法进行操作,但没有成功(可能是我做错了)?

我还尝试使用以下代码段强制设置下一个RecyclerView项目的下一个焦点:

@Override
public void onBindViewHolder(BaseFormViewHolder viewHolder, int index) {
    // (omitted stuffs)
    RecyclerView.ViewHolder previousViewHolder = getRecyclerView().findViewHolderForAdapterPosition(index -1);
    if(previousViewHolder != null)
        previousViewHolder.itemView.setNextFocusDownId(viewHolder.itemView.getId());

}

另一个信息是,我使用Stetho来分析我的布局,并发现在DynamicRadioGroupAccessibility Properties下面,出现了以下信息:

android focus search returned a view that wasn't able to take focus!

不确定该怎么办,但这可能有所帮助。


太长不看

即使我在这里没有得到完整的答案,我也想通过回答不同问题来更好地理解它是如何工作的:

  • 如何使自定义视图/自定义ViewGroup focusable并在获取/失去焦点时做出反应。
  • 如何强制让RecyclerView中的View指向下一个项目,涉及nextFocus
  • 上面的堆栈跟踪真正意味着什么?
  • Stetho检查器中的消息真正意味着什么?

谢谢阅读!


这个答案可能会有帮助 https://dev59.com/sGYr5IYBdhLWcg3wg6f9#49433332 - snersesyan
2个回答

0

EditorInfo.IME_ACTION_NEXT选项的值和下一个找到的对象不可聚焦或其父对象不可聚焦时,会发生此错误。

正如IME_ACTION_NEXT的文档中所提到的here

IME_MASK_ACTION的位:操作键执行“下一个”操作, 将用户带到将接受文本的下一个字段。

因此,它调用查找下一个应转移焦点的项目,但是此下一个视图不存在或无法聚焦,或者父级实际上无法处理findFocus()调用并返回null。

因此,在您的情况下,如果您的自定义类扩展了RadioGroup,该类又扩展了LinearLayout,因此您需要将您的自定义视图设置为clickablefocusabletrue, 以便可以处理焦点请求。


0

我在您自定义视图的构造函数或XML中没有看到以下两个函数,要使视图可聚焦,您需要这些函数:

setFocusable(true);
setClickable(true);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接