민희의 코딩일지

[Android] 안드로이드스튜디오 검색 자동완성 AutoCompleteTextView 본문

Android

[Android] 안드로이드스튜디오 검색 자동완성 AutoCompleteTextView

heehminh 2022. 1. 22. 14:40
반응형

AutoCompleteTextView 

<AutoCompleteTextView

첫 단어부터 일치해야 검색 가능

ex) '김민희' 를 검색하려면 '김민'으로 검색 -> 자동완성어로 '김민희' 제시/ '민희' 를 입력했다면 '김민희' 추천X

 

속성

android:completionThreshold="2"

최소 2글자이상 입력시에 자동완성어 추천

 

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

<예시로 만든 프로젝트>

너무 허접이라 private로 설정해두었는데 혹시라도 궁금하신 분 계시다면 댓글 남겨주세요 public으로 풀게요! (아직 내 블로그 조회수 total 0이지만.. 나중에 유명해질 수도 있으니... )

https://github.com/heehminh/AutoComplete 

 

1) search_bar.xml

<androidx.cardview.widget.CardView
<androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:layout_gravity="center">
        
        <AutoCompleteTextView
            android:id="@+id/auto_tv"
            android:layout_width="0dp"
            android:layout_height="40dp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:maxLines="3"
            android:hint="검색할 단어를 입력해주세요." />

    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.cardview.widget.CardView>

 

2) activity_main.xml

<include
    android:id="@+id/search_bar"
    layout = "@layout/search_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

id enroll_text TextView (단어 등록)

id enroll_input EditText 

id enroll_btn Button (단어 등록하기)

-> enroll_input에 단어를 작성하고 enroll_btn을 클릭하면 자동완성 리스트에 단어가 들어감

 

3) MainActivity

val wordList = mutableListOf<String>()

자동완성 단어 목록 list를 생성해준다. 

 

search_bar.auto_tv.threshold = 1

단어 글자수가 1미만이면 그 단어는 무시함

 

enroll_btn.setOnClickListener {
    wordList.add(enroll_input.text.toString())
    val adapter = ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, wordList)
    search_bar.auto_tv.setAdapter(adapter)

    enroll_input.setText("")
}

 

반응형
Comments