Update ListView Textview vom Asyntask

2019-09-14 22:01发布

i need to update a textView from my asynctask. I have an custom adapter for the listview and there i want to have a countdown for each entry. I will start the asynctask for each entry from my Adapter. How can i update the textview each second from the asynctask?

Thanks for help :)

2条回答
叼着烟拽天下
2楼-- · 2019-09-14 22:23

You can do something like this (this will add an entry to a list view every one second). I have used the normal ArrayAdapter to add a string. You can use your custom adapter to do something similar. The publishProgress() method basically triggers the onProgressUpdate() method which hooks to the UI thread and displays the elements getting added.:

class AddStringTask extends AsyncTask {

    @Override
    protected Void doInBackground(Void... params) {
        for(String item : items) {
            publishProgress(item);
            SystemClock.sleep(1000);
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(String... item) {
        adapter.add(item[0]);
    }

    @Override
    protected void onPostExecute(Void unused) {
        Toast.makeText(getActivity(), "Done adding string item", Toast.LENGTH_SHORT).show();
    }
}
查看更多
相关推荐>>
3楼-- · 2019-09-14 22:41

If you post your code, I can give you a better answer. However, a common way to update views periodically is by using Handlers.

private final Handler mHandler = new Handler(); //intialize in main thread

public void test() {
    mHandler.postDelayed(new Runnable() {

        @Override
        public void run() {
            mTextView.setText("hello");

        }
    }, 1000);
}
查看更多
登录 后发表回答