package com.example.chemical.utils

import android.content.Context
import android.util.AttributeSet
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager

class CustomEditText : androidx.appcompat.widget.AppCompatEditText {

    constructor(context: Context) : super(context)

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    override fun onEditorAction(actionCode: Int) {
        super.onEditorAction(actionCode)
        if (actionCode == EditorInfo.IME_ACTION_DONE ||
            actionCode == EditorInfo.IME_ACTION_NEXT ||
            (actionCode == EditorInfo.IME_NULL &&
                    KeyEvent.keyCodeToString(KeyEvent.KEYCODE_ENTER) == "\n")
        ) {
            // 关闭软键盘
            hideSoftKeyboard()
        }
    }

    private fun hideSoftKeyboard() {
        val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(windowToken, 0)
    }
}