본문 바로가기
안드로이드/Widget

안드로이드 TextInputLayout

by 김어찐 2022. 5. 30.
728x90

EditText를 보완한 View이다.
EditText의 속성, 이벤트, 프로퍼티 등을 그대로 사용하며 몇 가지 요소가 추가되었다.

 

주요 속성

hint : 입력한 내용이 없으면 보여줄 안내 메시지이다. EditText와 다르게 문자열을 입력하면 상단 부분으로 올라간다.
counterEnabled : 입력한 글자의 수가 나타난다.
counterMaxLength : 지정한 글자수를 넘으면 붉은 색으로 표시해준다.

주요 프로퍼티

editText : TextInputLayout이 가지고 있는 EditText 객체의 주소 값
error : 오류로 표시할 메시지를 설정한다.

 

package com.example.textinputlayout

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.inputmethod.InputMethodManager
import androidx.core.widget.addTextChangedListener
import kotlinx.android.synthetic.main.activity_main.*

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

        button1.setOnClickListener {
            textView1.text = textInputLayout1.editText?.text


            // 엔터시 포커스 제거거
           textInputLayout1.editText?.clearFocus()
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(textInputLayout1.editText?.windowToken,0)
        }
        textInputLayout1.editText?.addTextChangedListener(listner1)
    }

    val listner1 = object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }

        override fun afterTextChanged(s: Editable?) {
            if (s != null) {
                if (s.length > 10) {
                    textInputLayout1.error = "10 글자 이하로 입력해주세요"
                } else {
                    textInputLayout1.error = null
                }
            }
        }
    }
}

728x90

'안드로이드 > Widget' 카테고리의 다른 글

안드로이드 ToggleButton  (0) 2022.05.30
안드로이드 ImageView  (0) 2022.05.30
안드로이드 EditText  (0) 2022.05.27
안드로이드 Button  (0) 2022.05.27
안드로이드 TextView  (0) 2022.05.27