基于ArrayAdapter的EditText AutoComplete

时间:2017-11-30 10:54:45

标签: android autocomplete android-edittext android-arrayadapter

我有一个片段活动,调用AutoComplete EditText函数,这里是我的代码onCreateView

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_pegawai, container, false);

    textAutoComplete = v.findViewById(R.id.autoCompleteTextView1);
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, heroes);
    textAutoComplete.setAdapter(arrayAdapter);
    textAutoComplete.setThreshold(1);

    listView = v.findViewById(R.id.DaftarTextViewNamaPegawai);

    return v;
}

我在ArrayAdapter中混淆了调用字符串英雄。我设置了这样的功能

private void getJSON(final String urlWebService) {

    class GetJSON extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }


        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Toast.makeText(getContext(), s, Toast.LENGTH_SHORT).show();
            try {
                loadIntoListView(s);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        protected String doInBackground(Void... voids) {
            try {
                URL url = new URL(urlWebService);
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                StringBuilder sb = new StringBuilder();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String json;
                while ((json = bufferedReader.readLine()) != null) {
                    sb.append(json + "\n");
                }
                return sb.toString().trim();
            } catch (Exception e) {
                return null;
            }
        }
    }
    GetJSON getJSON = new GetJSON();
    getJSON.execute();
}

private void loadIntoListView(String json) throws JSONException {
    JSONArray jsonArray = new JSONArray(json);
    String[] heroes = new String[jsonArray.length()];
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject obj = jsonArray.getJSONObject(i);
        heroes[i] = obj.getString("name");
    }
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, heroes);
    listView.setAdapter(arrayAdapter);
}

但是当我尝试在EditText中键入文本时,它不是自动完成。 有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:0)

您可以在写下3行代码后填写listview。

 ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, heroes);
         textAutoComplete.setAdapter(arrayAdapter);
         textAutoComplete.setThreshold(1);