How to update progressbar in a ListView item

拟墨画扇 提交于 2019-12-02 18:44:54

This is the way I finally solved it (after many iterations and different implementations). It's a bit tricky but basically you need three things:

  1. An AsyncTask that gathers meta data
  2. A scroll listener that tells us when the user has stopped scrolling/flinging
  3. A clever algorithm that finds any visible row that needs updating and asks the adapter to only update that specific row

This is the way I designed and implemented it:

I wrote in more detail about it here, and please see the github code for the complete imlementation.

    private class UpdaterAsyncTask extends AsyncTask<Void, Void, Void> {

    boolean isRunning = true;

    public void stop() {
        isRunning = false;
    }

    @Override
    protected Void doInBackground(Void... params) {

        while (isRunning) {

            // Gather data about your adapter objects
            // If an object has changed, mark it as dirty                

            publishProgress();

            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    @Override
    protected void onProgressUpdate(Void... params) {
        super.onProgressUpdate();

        // Update only when we're not scrolling, and only for visible views
        if (mScrollState == OnScrollListener.SCROLL_STATE_IDLE) {
            int start = mListview.getFirstVisiblePosition();
            for(int i = start, j = mListview.getLastVisiblePosition(); i<=j; i++) {
                View view = mListview.getChildAt(i-start);
                if (((Content)mListview.getItemAtPosition(i)).dirty) {
                    mListview.getAdapter().getView(i, view, mListview); // Tell the adapter to update this view
                }

            }
        }

      }
    }

For a specific view item, you can retrieve it using getChildAt(int index) and update it.

And you can traverse through all visible items by the help of getFirstVisiblePosition() and getLastVisiblePosition()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!