移动搜索栏不流畅

Move Seekbar not smooth

我有 Seekbar,我实现的源代码如下:

        seekProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            adjustCombination(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

因为函数:adjustCombination(progress)需要0.2秒才能执行完,所以当我移动Seekbar时,它不流畅。那么我该如何解决这个问题呢?

不要在 UI 线程上执行此操作。而是创建一个后台线程,并处理回调。如果需要,然后在 UI 线程上更新您的 UI。

new AsyncTask<Void, Void, Void>() {
    @Override
    protected Void doInBackground(Void... params) {
        // your async action
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        // update the UI (this is executed on UI thread)
        super.onPostExecute(aVoid);
    }
}.execute();

您可以像这样使用 AsyncTask 执行后台任务,

seekProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            new getData().execute(progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

现在,您必须定义 getData() 来执行和传递您需要的参数。在你的情况下,我们必须通过进度,

private class getData extends AsyncTask<String, Void, String> {

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

    @Override
    protected String doInBackground(String... progress) {
        // perform operation you want with String "progress"
        String value = "hello" + progress;
        return value;
    }

    @Override
    protected void onPostExecute(String progressResult) {
        // do whatever you want in this thread like
        // textview.setText(progressResult)
        super.onPostExecute(progressResult);
    }
}

so, PreExecute method will be executed before performing any task in background, then your doInBackground method will be called and you will get arguments pass in this method after doInBackground onPostExecute method will be called which will receive the result returned from the doInBackground method. I hope you get it.

如果合适,将你的计算代码移到onStopTrackingTouch()方法中。这样当你停止在搜索栏上滑动时它只会被调用一次。