【问题标题】:Android AutoCompleteTextView : Perform a AsyncTask call only once on TextChangeAndroid AutoCompleteTextView:仅在 TextChange 上执行一次 AsyncTask 调用
【发布时间】:2016-08-02 13:47:53
【问题描述】:

我的布局中有一个 AutoCompleteTextView。用户输入第一个字符后,我想做一个 API 调用,我在 AsyncTask 中进行。我使用了 addTextChangedListener 并且正在对 TextChanged 进行 API 调用。但问题是每次用户对 AutoCompleteTextView 进行任何更改时,API 调用都会完成。

但我希望 API 调用只发生一次,即在输入第一个字符之后。我如何做到这一点?

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_places_search);
    search_airport = (AutoCompleteTextView) findViewById(R.id.place_search);
    autocompleteadapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, airports);
    search_airport.setAdapter(autocompleteadapter);
    search_airport.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) {
            mAirport = new AsyncTaskAirport(search_airport.getEditableText().toString().substring(0, 1));
            mAirport.execute((Void) null);

        }

        @Override
        public void afterTextChanged(Editable s) {


        }
    });


}

【问题讨论】:

  • 如果用户输入一个字符,然后删除它,然后输入另一个字符怎么办?如果用户输入一个字符,然后返回到第一个位置并在第一个字符之前插入另一个字符怎么办?
  • @DougStevenson 是的......我也必须考虑这些情况......你能告诉我如何实现所有这些场景吗?

标签: android android-asynctask autocomplete


【解决方案1】:

试试这个,

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
    if(s.toString().trim().length()==1){
       mAirport = new AsyncTaskAirport(search_airport.getEditableText().toString().substring(0, 1));
       mAirport.execute((Void) null);
     }

 }

【讨论】:

  • 面部护理。谢谢。优雅而简单的解决方案。
【解决方案2】:

你可以用计时器解决你的问题。这里是如何

@Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
    int COMPLETION_DELAY = 2000;
    if (timer != null)
    {
        timer.cancel();
        timer.purge();
        timer = null;
    }
    timer = new Timer();
    timer.schedule(new TimerTask()
    {
        @Override
        public void run()
        {
            new Handler(Looper.getMainLooper()).post(new Runnable()
            {
                @Override
                public void run()
                {
                    if (s.toString().length() >= appCompatAutoCompleteTextView.getThreshold())
                    {
                         //CALL WebService Here
                    }
                }
            });
        }
    }, COMPLETION_DELAY);
}

现在,当用户在输入自动完成时进行更改时,您的服务将不会被调用。服务只会在用户停止 + 2 秒后被调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多