How to dynamically add suggestions to autocompletetextview with preserving character status

后端 未结 2 2033
小蘑菇
小蘑菇 2020-11-21 06:41

Problem Description:

I am facing some problem with AutoCompleteTextView where I have to show suggestions after each keypress. Thing is that, list of

2条回答
  •  旧时难觅i
    2020-11-21 07:28

    one of the easiest way of doing that (put the code in onCreate):

    EDIT: addied wikipedia free opensearch (if https://en.wikipedia.org doesn't work try http://en.wikipedia.org)

        AutoCompleteTextView actv = new AutoCompleteTextView(this);
        actv.setThreshold(1);
        String[] from = { "name", "description" };
        int[] to = { android.R.id.text1, android.R.id.text2 };
        SimpleCursorAdapter a = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, null, from, to, 0);
        a.setStringConversionColumn(1);
        FilterQueryProvider provider = new FilterQueryProvider() {
            @Override
            public Cursor runQuery(CharSequence constraint) {
                // run in the background thread
                Log.d(TAG, "runQuery constraint: " + constraint);
                if (constraint == null) {
                    return null;
                }
                String[] columnNames = { BaseColumns._ID, "name", "description" };
                MatrixCursor c = new MatrixCursor(columnNames);
                try {
                    String urlString = "https://en.wikipedia.org/w/api.php?" +
                            "action=opensearch&search=" + constraint +
                            "&limit=8&namespace=0&format=json";
                    URL url = new URL(urlString);
                    InputStream stream = url.openStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
                    String jsonStr = reader.readLine();
                    // output ["query", ["n0", "n1", ..], ["d0", "d1", ..]]
                    JSONArray json = new JSONArray(jsonStr);
                    JSONArray names = json.getJSONArray(1);
                    JSONArray descriptions = json.getJSONArray(2);
                    for (int i = 0; i < names.length(); i++) {
                        c.newRow().add(i).add(names.getString(i)).add(descriptions.getString(i));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return c;
            }
        };
        a.setFilterQueryProvider(provider);
        actv.setAdapter(a);
        setContentView(actv, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    

提交回复
热议问题