接下来重点介绍RecyclerView中的自定义视图

时间:2018-11-28 15:23:29

标签: android android-recyclerview focus android-view

我有RecyclerView代表表格。这些RecyclerViewView的多种类型组成。根据它们表示的数据类型,每个都有一个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>

当上述自定义类型字段前面带有字符串类型时,当我们在聚焦字符串类型字段时点击键盘的 next 按钮时,应用程序崩溃。

崩溃堆栈跟踪:

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分析了自己的布局,并在Accessibility Properties的{​​{1}}下找到了以下消息:

  

android焦点搜索返回的视图无法获得焦点!

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


TL; DR

即使我在这里没有得到完整的答案,我也想通过获取不同问题的答案来更好地了解其工作原理:

  • 如何创建自定义View /自定义ViewGroup DynamicRadioGroup,并对焦点的增益/丢失做出反应。
  • 在谈论focusable时,如何强制View内的RecyclerView指向下一项。
  • 上面的stacktrace到底是什么意思?
  • nextFocus检查器中的消息是什么意思?

感谢您的阅读!

2 个答案:

答案 0 :(得分:0)

我没有在自定义视图或xml的构造函数中看到以下两个函数,而要使视图可聚焦,则需要这些函数。 setFocusable(true); setClickable(true);

答案 1 :(得分:0)

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

IME_ACTION_NEXT here

的文档中所述
  

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

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

因此,在您的情况下,如果您的自定义类是从 RadioGroup 扩展而来的,而扩展了LinearLayout ,那么您需要将自定义视图设置为clickablefocusable设为 true ,以便它可以处理焦点请求。