Created
September 27, 2018 11:57
-
-
Save BoxResin/ac0bc9eddc2cdaf62d301f9fb941e62b to your computer and use it in GitHub Desktop.
급식 앱 - 학교 검색 SearchView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package winapi251.app.schoolmeal.ui.main | |
import android.content.Context | |
import android.database.MatrixCursor | |
import android.util.Log | |
import androidx.appcompat.widget.SearchView | |
import androidx.cursoradapter.widget.SimpleCursorAdapter | |
import kotlinx.coroutines.experimental.Dispatchers | |
import kotlinx.coroutines.experimental.GlobalScope | |
import kotlinx.coroutines.experimental.android.Main | |
import kotlinx.coroutines.experimental.launch | |
import winapi251.app.schoolmeal.R | |
import winapi251.app.schoolmeal.model.school.School | |
import winapi251.app.schoolmeal.model.school.SchoolApi | |
/** 툴바의 학교 검색 뷰 */ | |
class SchoolSearchView(context: Context) : SearchView(context), SearchView.OnQueryTextListener, | |
SearchView.OnSuggestionListener | |
{ | |
private val columns = arrayOf("_id", "name", "address") | |
private val viewIds = intArrayOf(-1, R.id.txt_school_name, R.id.txt_school_address) | |
init { | |
// 힌트 초기화 | |
queryHint = context.getString(R.string.action_search_school_hint) | |
// 드롭다운 초기화 | |
suggestionsAdapter = SimpleCursorAdapter(context, R.layout.item_school_search_result, | |
MatrixCursor(columns), columns, viewIds) | |
// 리스너 초기화 | |
setOnQueryTextListener(this) | |
setOnSuggestionListener(this) | |
} | |
/** 사용자가 검색어를 변경할 때마다 호출된다. */ | |
override fun onQueryTextChange(newText: String) = false | |
/** | |
* 사용자가 검색 버튼을 누를 때 호출된다. | |
* @return true - 사용자가 검색 버튼을 누른 뒤 키보드가 내려가지 않게 한다. | |
*/ | |
override fun onQueryTextSubmit(query: String): Boolean | |
{ | |
// 학교를 검색하고 드롭다운에 반영한다. | |
GlobalScope.launch(Dispatchers.Main) { | |
val result: List<School> = SchoolApi.search(query) | |
// 검색 결과를 Cursor 화 | |
val cursor = MatrixCursor(columns).apply { | |
result.forEachIndexed { index: Int, school -> | |
addRow(arrayOf("$index", school.name, school.address)) | |
} | |
} | |
suggestionsAdapter.changeCursor(cursor) | |
} | |
return true | |
} | |
override fun onSuggestionSelect(position: Int) = false | |
/** 사용자가 드롭다운 Item 을 선택할 때 호출된다. */ | |
override fun onSuggestionClick(position: Int): Boolean | |
{ | |
Log.i("ASDF", "$position") | |
return false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment