Created
July 10, 2016 12:26
-
-
Save vmax/f2ef9a7bdf55b1194c0345c2d51f3146 to your computer and use it in GitHub Desktop.
AutoCompleteTextView that delays sending requests to adapter (needed if suggestions are being queried from external API). Also shows progress bar when loading suggestions.
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
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; | |
public class DelayAutoCompleteTextView extends AutoCompleteTextView { | |
private static final int MESSAGE_TEXT_CHANGED = 100; | |
private static final int DEFAULT_AUTOCOMPLETE_DELAY = 750; | |
private int mAutoCompleteDelay = DEFAULT_AUTOCOMPLETE_DELAY; | |
private ProgressBar mLoadingIndicator; | |
private final Handler mHandler = new Handler() { | |
@Override | |
public void handleMessage(Message msg) { | |
DelayAutoCompleteTextView.super.performFiltering((CharSequence) msg.obj, msg.arg1); | |
} | |
}; | |
public DelayAutoCompleteTextView(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
} | |
public void setLoadingIndicator(ProgressBar progressBar) { | |
mLoadingIndicator = progressBar; | |
} | |
public void setAutoCompleteDelay(int autoCompleteDelay) { | |
mAutoCompleteDelay = autoCompleteDelay; | |
} | |
@Override | |
protected void performFiltering(CharSequence text, int keyCode) { | |
if (mLoadingIndicator != null) { | |
mLoadingIndicator.setVisibility(View.VISIBLE); | |
} | |
mHandler.removeMessages(MESSAGE_TEXT_CHANGED); | |
mHandler.sendMessageDelayed(mHandler.obtainMessage(MESSAGE_TEXT_CHANGED, text), mAutoCompleteDelay); | |
} | |
@Override | |
public void onFilterComplete(int count) { | |
if (mLoadingIndicator != null) { | |
mLoadingIndicator.setVisibility(View.GONE); | |
} | |
super.onFilterComplete(count); | |
} | |
} | |
// code sample | |
location.setLoadingIndicator((ProgressBar)findViewById(R.id.progress_bar_id)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment