안드로이드 코틀린

[Android][kotlin] EditText Submit처럼 사용하기

teamnova 2022. 4. 6. 12:00
728x90

안녕하세요. 오늘은 EditText 텍스트에 Enter 키를 입력받도록 적용해보겠습니다.

 

1. Activity를 생성합니다.

2. Activity의 레이아웃에 사용자의 input을 받을 EditText와, 결과를 나타낼 textView를 생성합니다.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.rai.MainActivity">

    <EditText
        android:id="@+id/input"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="124dp"
        android:layout_marginLeft="124dp"
        android:layout_marginTop="392dp"
        android:hint="입력해주세요."
        android:singleLine="true"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="40dp"
        android:layout_marginLeft="40dp"
        android:layout_marginTop="120dp"
        android:text="결과 : "
        android:textSize="20sp"
        app:layout_constraintStart_toStartOf="@+id/input"
        app:layout_constraintTop_toBottomOf="@+id/input" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

3. EditText가 있는 Activity에 작성합니다.

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val editText = findViewById<EditText>(R.id.input)
        val textView = findViewById<TextView>(R.id.result)

        editText.setOnKeyListener { v, keyCode, event ->
            if ((keyCode == KeyEvent.KEYCODE_ENTER)) {
                val keyword: String by lazy {
                    if (editText.text.toString().isNullOrEmpty()) {
                        return@lazy ""
                    } else {
                        return@lazy ""
                    }
                }

                editText.clearFocus()
                editText.requestFocus()
                textView.text = keyword
            }
            return@setOnKeyListener false
            
        }
    }

결과

 

+ 몇 가지

 

1. 가상키보드가 올라갈 때 화면 비율이 조정이 안 되었으면 좋겠어요.

Manifest파일에서사용하는 Activity에 windowSoftInputMode 속성을 추가합니다.

        <activity android:name=".MainActivity"
            android:exported="true"
            android:windowSoftInputMode="adjustNothing">

 

2. EditText 바깥 범위를 눌렀을 때, EditText에 대한 focus가 사라지면서 가상 키보드를 닫고 싶어요.

: 사용하는 Activity에 다음 메서드를 오버라이딩합니다.

 override fun dispatchTouchEvent(event: MotionEvent): Boolean {
        if (event.action == MotionEvent.ACTION_DOWN) {
            val v: View? = currentFocus
            if (v is EditText) {
                val outRect = Rect()
                v.getGlobalVisibleRect(outRect)
                if (!outRect.contains(event.rawX.toInt(), event.rawY.toInt())) {
                    v.clearFocus()
                    val imm: InputMethodManager = getSystemService<Any>(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0)
                }
            }
        }
        return super.dispatchTouchEvent(event)
    }