Jak korzystać z AutoCompleteTextView i wypełniać go danymi z web API?
Chcę użyć AutoCompleteTextView
w mojej aktywności i wypełnić dane jako typy użytkowników poprzez zapytanie API www. Jak mam to zrobić?
Czy utworzyć nową klasę i nadpisać AutoCompleteTextView.performFiltering
, Czy użyć niestandardowego adaptera listy i podać Niestandardowy android.widget.Filter
, który nadpisuje performFiltering?
Czy jest lepszy sposób, aby osiągnąć mój cel końcowy?
Zrobiłem coś nieco podobnego, ale było to dla szybkiego wyszukiwania i wymagało wdrożenia usługi, ale wierzę, że nie tego chcę tutaj robić.
3 answers
Wymyśliłem rozwiązanie, Nie wiem, czy to najlepsze rozwiązanie, ale wygląda na to, że działa bardzo dobrze. Co zrobiłem został stworzony Niestandardowy adapter, który rozszerza ArrayAdapter. W niestandardowym adapterze nadpisałem getFilter i stworzyłem własną klasę filtrów, która nadpisuje performfilter. To rozpoczyna nowy wątek, więc nie przerywa interfejsu użytkownika. Poniżej znajduje się przykład barebones.
Moja aktywność.javapublic class MyActivity extends Activity {
private AutoCompleteTextView style;
@Override
public void onCreate(Bundle savedInstanceState) {
...
style = (AutoCompleteTextView) findViewById(R.id.style);
adapter = new AutoCompleteAdapter(this, android.R.layout.simple_dropdown_item_1line);
style.setAdapter(adapter);
}
}
AutoCompleteAdapter.java
public class AutoCompleteAdapter extends ArrayAdapter<Style> implements Filterable {
private ArrayList<Style> mData;
public AutoCompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
mData = new ArrayList<Style>();
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Style getItem(int index) {
return mData.get(index);
}
@Override
public Filter getFilter() {
Filter myFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if(constraint != null) {
// A class that queries a web API, parses the data and returns an ArrayList<Style>
StyleFetcher fetcher = new StyleFetcher();
try {
mData = fetcher.retrieveResults(constraint.toString());
}
catch(Exception e) {
Log.e("myException", e.getMessage());
}
// Now assign the values and count to the FilterResults object
filterResults.values = mData;
filterResults.count = mData.size();
}
return filterResults;
}
@Override
protected void publishResults(CharSequence contraint, FilterResults results) {
if(results != null && results.count > 0) {
notifyDataSetChanged();
}
else {
notifyDataSetInvalidated();
}
}
};
return myFilter;
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-10 17:57:41
Rozszerzenie na AJ.'s odpowiedź powyżej, następujący Adapter Niestandardowy zawiera obsługę żądań serwera i parsowanie json, jak również:
class AutoCompleteAdapter extends ArrayAdapter<String> implements Filterable
{
private ArrayList<String> data;
private final String server = "http://myserver/script.php?query=";
AutoCompleteAdapter (@NonNull Context context, @LayoutRes int resource)
{
super (context, resource);
this.data = new ArrayList<>();
}
@Override
public int getCount()
{
return data.size();
}
@Nullable
@Override
public String getItem (int position)
{
return data.get (position);
}
@NonNull
@Override
public Filter getFilter()
{
return new Filter()
{
@Override
protected FilterResults performFiltering (CharSequence constraint)
{
FilterResults results = new FilterResults();
if (constraint != null)
{
HttpURLConnection conn = null;
InputStream input = null;
try
{
URL url = new URL (server + constraint.toString());
conn = (HttpURLConnection) url.openConnection();
input = conn.getInputStream();
InputStreamReader reader = new InputStreamReader (input, "UTF-8");
BufferedReader buffer = new BufferedReader (reader, 8192);
StringBuilder builder = new StringBuilder();
String line;
while ((line = buffer.readLine()) != null)
{
builder.append (line);
}
JSONArray terms = new JSONArray (builder.toString());
ArrayList<String> suggestions = new ArrayList<>();
for (int ind = 0; ind < terms.length(); ind++)
{
String term = terms.getString (ind);
suggestions.add (term);
}
results.values = suggestions;
results.count = suggestions.size();
data = suggestions;
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (input != null)
{
try
{
input.close();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
if (conn != null) conn.disconnect();
}
}
return results;
}
@Override
protected void publishResults (CharSequence constraint, FilterResults results)
{
if (results != null && results.count > 0)
{
notifyDataSetChanged();
}
else notifyDataSetInvalidated();
}
};
}
I użyj go w ten sam sposób:
public class MyActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState) {
...
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById (R.id.style);
int layout = android.R.layout.simple_list_item_1;
AutoCompleteAdapter adapter = new AutoCompleteAdapter (this, layout);
textView.setAdapter (adapter);
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:10:06
Chu: aby dostosować wygląd widoku i uzyskać większą kontrolę nad rozpakowywaniem obiektu, wykonaj następujące czynności...
@Override
public View getView (int position, View convertView, ViewGroup parent) {
TextView originalView = (TextView) super.getView(position, convertView, parent); // Get the original view
final LayoutInflater inflater = LayoutInflater.from(getContext());
final TextView view = (TextView) inflater.inflate(android.R.layout.simple_dropdown_item_1line, parent, false);
// Start tweaking
view.setText(originalView.getText());
view.setTextColor(R.color.black); // also useful if you have a color scheme that makes the text show up white
view.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10); // override the text size
return view;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-05 04:17:59