簡體   English   中英

onFocusChange 事件未按預期工作

[英]onFocusChange event doesn't work as expected

我的問題是關於 Android/Java 的。

在我的 main.xml 中,我有兩個視圖:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:layout_width="wrap_content"
        android:inputType="textEmailAddress"
        android:layout_height="wrap_content"
        android:ems="10"
        android:id="@+id/mainEditText1"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"/>

</LinearLayout>

在我的 MainActivity.java 中,我設置了 OnFocusChangeListener:

    et.setOnFocusChangeListener(new OnFocusChangeListener() {
    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if (!hasFocus) {
            et.setError("Lost the focus");
        }
    }
});

當我單擊該按鈕時,應該會顯示一條錯誤消息,因為我要離開 EditText。 但事實並非如此。 為什么? 哪里有問題?

單擊您的按鈕,從edittext中清除焦點。

在編輯文本后將<requestFocus />添加到 xml。

android:focusable="true"android:focusableInTouchMode="true"添加到您的 Edittext。

示例 XML 代碼:

        <LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <EditText
                android:layout_width="wrap_content"
                android:ems="5"
                android:layout_height="wrap_content"
                android:id="@+id/mainEditText1"
                android:focusable="true"
                android:focusableInTouchMode="true"/>
            <requestFocus />
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Button"
                android:id="@+id/mainButton1"/>
        </LinearLayout>

在您的 java 文件中添加此代碼:

 e.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (!hasFocus) {
                    e.setError("Lost the focus");
                }else{
                    b.clearFocus();
                }
            }
        });
        b.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                e.clearFocus();
            }
        });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM