首页 > 解决方案 > Kotlin - 如何知道editText是否失去焦点

问题描述

在我的应用程序中,我需要能够捕捉到editText失去焦点的情况,我已经找到了如何在 java 中做到这一点,但我不太能够在 kotlin 中找到如何做到这一点。

我找到的 Java 答案是这个

 EditText txtEdit = (EditText) findViewById(R.id.edittxt);

 txtEdit.setOnFocusChangeListener(new OnFocusChangeListener() {          
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (!hasFocus) {
               // code to execute when EditText loses focus
            }
        }
    });

谁能帮我把它转换成 kotlin?

标签: androidkotlin

解决方案


这边走

// Class level
lateinit var editText: EditText


// Method onCreate/onCreateView
editText = findViewById(R.id.whatever)


editText.setOnFocusChangeListener { view, hasFocus ->
    if(!hasFocus) {

    }
}

推荐阅读