Last active
March 2, 2018 10:51
-
-
Save rubenpla-develop/153c8db856dbcb474e350493aaeea9ae to your computer and use it in GitHub Desktop.
CUstom view based on AutoCompleteTexview, with automatic delay and progress bar included. #Kotlin #CustomView #Android
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 rubenpla.develop.autocompletetextview_sample | |
import android.annotation.SuppressLint | |
import android.content.Context | |
import android.os.Handler | |
import android.os.Message | |
import android.util.AttributeSet | |
import android.view.View | |
import android.widget.AutoCompleteTextView | |
import android.widget.ProgressBar | |
class AutoCompleteTextViewWithDelay(context: Context, attrs: AttributeSet?) | |
: AutoCompleteTextView(context, attrs) { | |
private var autoCompleteDelay = DEFAULT_AUTOCOMPLETE_DELAY | |
private var loadingIndicator: ProgressBar? = null | |
private val autoCompleteHandler = @SuppressLint("HandlerLeak") | |
object : Handler() { | |
override fun handleMessage(msg: Message) { | |
super@AutoCompleteTextViewWithDelay.performFiltering(msg.obj as CharSequence, msg.arg1) | |
} | |
} | |
override fun enoughToFilter(): Boolean { | |
return !text.isNullOrEmpty() | |
} | |
fun setLoadingIndicator(progressBar: ProgressBar) { | |
loadingIndicator = progressBar | |
} | |
fun setAutoCompleteDelay(delay : Int) { | |
autoCompleteDelay = delay | |
} | |
override fun performFiltering(text: CharSequence?, keyCode: Int) { | |
if (loadingIndicator != null) { | |
loadingIndicator!!.visibility = View.VISIBLE | |
} | |
autoCompleteHandler.removeMessages(MESSAGE_TEXT_CHANGED) | |
autoCompleteHandler.sendMessageDelayed(handler.obtainMessage(MESSAGE_TEXT_CHANGED, text), | |
autoCompleteDelay.toLong()) | |
} | |
override fun onFilterComplete(count: Int) { | |
if (loadingIndicator != null) { | |
loadingIndicator!!.visibility = View.GONE | |
} | |
super.onFilterComplete(count) | |
} | |
companion object { | |
const val MESSAGE_TEXT_CHANGED = 100 | |
const val DEFAULT_AUTOCOMPLETE_DELAY = 750 | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment