AutoCompleteTextView при нажатии на элемент, не установленный в AutoCompleteBox - PullRequest
0 голосов
/ 27 апреля 2018

Я хочу показать элемент в AutoCompleteTextView. Работает нормально, и все выпадающие элементы отображаются. но в соответствии с моими потребностями я не хочу устанавливать элемент в поле автозаполнения при нажатии элемента. Как я могу достичь этого?

public class AutoCompleteViewActvitiy extends Activity {
    AutoCompleteTextView autoCompleteTextView;
    String[] language;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.support_simple_spinner_dropdown_item);

//after calling this service then you will get resposne ...in post method
        new CallServiceForFetchResponseOfCategory().execute();

    }


    public class CallServiceForFetchResponseOfCategory extends AsyncTask<String, Void, String> {
        public static final String REQUEST_METHOD = "GET";
        public static final int READ_TIMEOUT = 15000;
        public static final int CONNECTION_TIMEOUT = 15000;

        @Override
        protected String doInBackground(String... params) {
            String stringUrl = params[0];
            String result;
            String inputLine;

            try {
                URL myUrl = new URL(stringUrl);
                HttpURLConnection connection = (HttpURLConnection)
                        myUrl.openConnection();
                connection.setRequestMethod(REQUEST_METHOD);
                connection.setReadTimeout(READ_TIMEOUT);
                connection.setConnectTimeout(CONNECTION_TIMEOUT);
                connection.connect();
                InputStreamReader streamReader = new
                        InputStreamReader(connection.getInputStream());
                BufferedReader reader = new BufferedReader(streamReader);
                StringBuilder stringBuilder = new StringBuilder();
                while ((inputLine = reader.readLine()) != null) {
                    stringBuilder.append(inputLine);
                }
                reader.close();
                streamReader.close();
                result = stringBuilder.toString();
            } catch (IOException e) {
                e.printStackTrace();
                result = null;
            }

            return result;
        }

        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            //in response you will get category array ....
            //like 
            then you will set array into this :
            language = .......;
            then
            setResponse();
        }

    }

    private void setResponse() {

        ArrayAdapter<String> adapter = new ArrayAdapter<String>
                (this, android.R.layout.select_dialog_item, language);
        //Getting the instance of AutoCompleteTextView
        autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
        autoCompleteTextView.setThreshold(1);//will start working from first character
        autoCompleteTextView.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
        autoCompleteTextView.setTextColor(Color.RED);

        autoCompleteTextView.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) {

            }

            @Override
            public void afterTextChanged(Editable s) {
// first srevice again and again call for fetching the result and show in autocomplete

                if (autoCompleteTextView.getText().toString().trim().length() > 0) {
                    new CallServiceForFetchResponseOfCategory().execute();

                }

            }
        });

autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

//according to id i will call this service but issue is that when i click on item it will set default in autocomplete text box and
        //again  afterTextChanged will call then again  CallServiceForFetchResponseOfCategory hit, that is the issue 
        // i dont want call this time CallServiceForFetchResponseOfCategory service when i click on item...
        new FetchingCityDataAsynkTask().execute();


    }
});
    }

//

    public class FetchingCityDataAsynkTask extends AsyncTask<String, Void, String> {
        public static final String REQUEST_METHOD = "GET";
        public static final int READ_TIMEOUT = 15000;
        public static final int CONNECTION_TIMEOUT = 15000;

        @Override
        protected String doInBackground(String... params) {
            String stringUrl = params[0];
            String result;
            String inputLine;

            try {
                URL myUrl = new URL(stringUrl);
                HttpURLConnection connection = (HttpURLConnection)
                        myUrl.openConnection();
                connection.setRequestMethod(REQUEST_METHOD);
                connection.setReadTimeout(READ_TIMEOUT);
                connection.setConnectTimeout(CONNECTION_TIMEOUT);
                connection.connect();
                InputStreamReader streamReader = new
                        InputStreamReader(connection.getInputStream());
                BufferedReader reader = new BufferedReader(streamReader);
                StringBuilder stringBuilder = new StringBuilder();
                while ((inputLine = reader.readLine()) != null) {
                    stringBuilder.append(inputLine);
                }
                reader.close();
                streamReader.close();
                result = stringBuilder.toString();
            } catch (IOException e) {
                e.printStackTrace();
                result = null;
            }

            return result;
        }

        protected void onPostExecute(String result) {
            super.onPostExecute(result);
      //setresponse here
        }

    }
}

1 Ответ

0 голосов
/ 27 апреля 2018

Вот что я сделал в моем проекте. Я просто помещаю текстовое значение AutoCompleteTextView в ""

articlesAutocomplete.setOnItemClickListener(
            (detailedArticleAdapterView, childView, position, id) ->{
                DetailedArticle selectedArticle = (DetailedArticle)detailedArticleAdapterView.getItemAtPosition(position);
                /*logic with selected article*/
                articlesAutocomplete.setText("");
            }
    );

Я надеюсь, что это то, чего вы хотели достичь:)

РЕДАКТИРОВАТЬ: Я видел в ваших комментариях, что вы используете TextWatcher, зачем вы его используете? Это может изменить полезность моего решения ^^

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...