How to implement autocompletetextview in Android Studio with an API call?

妖精的绣舞 提交于 2020-08-25 03:58:06

问题


I am trying to use the autocompletetextview in Android Studio to provide suggestions for every letter keyed-in by the user.

Every time a letter is keyed-in, an API call is made like this,

http://dev.markitondemand.com/MODApis/Api/v2/Lookup/json?input=app
http://dev.markitondemand.com/MODApis/Api/v2/Lookup/json?input=appl
http://dev.markitondemand.com/MODApis/Api/v2/Lookup/json?input=apple

The JSON array that's returned from the API call is populated in the suggestions list-box.

So far I got the activity_main.xml file like this,

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.raam.stockmarketviewer.MainActivity">

    <AutoCompleteTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/stocks"
        android:hint="@string/hint" />
</RelativeLayout>

After this how should I structure the MainActivity.java file to accomplish the auto-suggestions feature?


回答1:


Just create a simple adapter and update it every time you get results

  List<String> suggestions = new ArrayList<>();
  ArrayAdapter<String> adapter ;
   .
   .
   .
   // in your onCreate

   autocomplete = (AutoCompleteTextView)findViewById(R.id.stocks);
   adapter = new ArrayAdapter<>(this,
            android.R.layout.simple_dropdown_item_1line, suggestions);
   autocomplete.setAdapter(arrayAdapter);

   autocomplete.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
          //retrieveData(s);
        }

        @Override
        public void afterTextChanged(Editable s) {
            retrieveData(s); //this will call your method every time the user stops typing, if you want to call it for each letter, call it in onTextChanged 

        }
    });
   .
   .
   .
   // where you get the data, I suppose in a list
   private void retrieveData(String s){
    //Do your stuff here with the String s and store the list of your results in the list suggestions
   suggestions = yourList;
   adapter.notifyDataSetChanged();

   }


来源:https://stackoverflow.com/questions/36799746/how-to-implement-autocompletetextview-in-android-studio-with-an-api-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!