代码之家  ›  专栏  ›  技术社区  ›  Kemat Rochi

如何使用API调用在Android Studio中实现autocompletetextview?

  •  3
  • Kemat Rochi  · 技术社区  · 9 年前

    我正在尝试使用Android Studio中的autocompletetextview为用户键入的每个字母提供建议。

    每次键入字母时,都会进行这样的API调用,

    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
    

    从API调用返回的JSON数组将填充在建议列表框中。

    到目前为止,我得到了 activity_main.xml 这样的文件,

    <?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>
    

    在此之后,我应该如何构造 主活动.java 文件来完成自动建议功能?

    1 回复  |  直到 6 年前
        1
  •  8
  •   David Seroussi    9 年前

    只需创建一个简单的适配器,并在每次获得结果时更新它

      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();
    
       }