在 Samsung Galaxy Tab A 上,clearFocus on editText 调用两次 onFocusChange (Android API 24)

Flo*_*urs 5 xml android

在视图上,我有一个 LinearLayout,当我单击下面的 EditText 时,我想折叠它,然后在我们取消焦点时展开它。

<EditText
            android:layout_width="1000dp"
            android:layout_height="43dp"
            android:layout_centerVertical="true"
            android:textSize="14.4sp"
            android:gravity="center_vertical"
            android:hint="@string/hint_query"
            android:layout_toEndOf="@+id/searchImage"
            android:id="@+id/searchBoxText"
            android:background="@null"
            android:layout_marginStart="16dp"
            android:inputType="text"
            tools:ignore="Autofill" />
Run Code Online (Sandbox Code Playgroud)

感谢 Android-Annotations,我实现了一个 onFocusChangeListener。

@FocusChange
void searchBoxText(EditText searchBoxText) {
    Log.d("change focus", "focus has changed with " + searchBoxText.hasFocus());
    if (!searchBoxText.hasFocus()) {
        if(upperView != null)
            upperView.setVisibility(View.VISIBLE);
    } else {
        if(upperView != null)
            upperView.setVisibility(View.GONE);
    }
}
Run Code Online (Sandbox Code Playgroud)

我在父级上有一个 touchListener ,它抛出:

searchBoxText.clearFocus();
Run Code Online (Sandbox Code Playgroud)

当我们点击 EditText 之外的时候。

平板电脑我的目标是将此代码支持为最大 API 24。我的问题是此代码在 API 28 中完美运行,但在 API 24 上运行不佳,它会抛出 onFocusChange 两次,而且我没有找到任何原因来说明为什么这样做或任何让它发挥作用的方法。

Udi*_*hef 1

我认为发生的情况是:

  1. 用户离开第一个项目(因此焦点从第一个项目离开,因此焦点“正在更改”,因此触发 onFocuseChange 事件。

  2. 然后我们将焦点放在选定的第二项上,因此再次“focusCahnged”,因此再次调用 onFocuseChange 事件。所以你可以这样做:

                    public void onFocusChange(View v, boolean b) {
                               if (v.hasFocus()){
                                     v.performClick()); // or any other logic you need
                               } 
                     }
    
    Run Code Online (Sandbox Code Playgroud)

    那么它只会执行一次您需要的操作(当 v 获得焦点时)。

祝你好运 :-)