【问题标题】:How to show dropdown of AutoCompleteTextView after some seconds of last typed letter?如何在最后输入字母几秒钟后显示 AutoCompleteTextView 的下拉列表?
【发布时间】:2021-08-27 11:58:55
【问题描述】:

好吧,我必须调用 api 从服务器获取数据并显示在 AutoCompleteTextView 中。我可以完美地获取该搜索结果,但问题是,当我在 AutoCompleteTextView 中输入单个字母时,每次执行 api 时,这都不是很好的用户体验,而且需要太多时间。

虽然,我已经创建了一些逻辑来在几秒钟后获取数据,但它只在我输入下一个字母时才有效。

        String sec;
        
        home_name_search.addTextChangedListener(new TextWatcher() {

        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @RequiresApi(api = Build.VERSION_CODES.O)
        @Override
        public void afterTextChanged(Editable s) {
            Format sdf = new SimpleDateFormat("ss");
            if (s.length() >= 3) { // minimum 3 letters to execute api.
                if (s.length() == 3) {
                    sec = sdf.format(new Date());
                } else {
                    try {
                        SimpleDateFormat sdf2 = new SimpleDateFormat("ss");
                        String Cdate = sdf.format(new Date());
                        Date d1 = sdf2.parse(sec);
                        Date d2 = sdf2.parse(Cdate);
                        long CompareDate = d2.getTime() - d1.getTime();
                        if (CompareDate >= 3000) {
                            //here my api executes in AsyncTask.
                            sec = sdf.format(new Date());
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    });

【问题讨论】:

    标签: java android android-studio android-layout autocompletetextview


    【解决方案1】:

    你可以使用定时器来等待:

    Timer timer = new Timer();
    final long DELAY = 1000; // You can give the time(1000 =1 sec.)
    home_name_search.addTextChangedListener(
    new TextWatcher() {
        @Override public void onTextChanged(CharSequence s, int start, int before, int count) { }
        @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
        @Override
        public void afterTextChanged(final Editable s) {
            timer.cancel();
            timer = new Timer();
            timer.schedule(
                new TimerTask() {
                    @Override
                    public void run() {
                        // You can call API.
                    }
                },
                DELAY
            );
        }
    });
    

    【讨论】:

    • 谢谢,这很简单,但我把它弄复杂了......它的工作
    猜你喜欢
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 2011-12-30
    • 2014-09-08
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多