使用计时器更新列表 UI [英] Updating the List UI with Timer

查看:35
本文介绍了使用计时器更新列表 UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 timer 更新 ListView.我已经实现了 android UI 计时器,但我的问题是如何将它用于 ListView,我需要在特定时间间隔后更新列表的每一行.处理程序将如何更新列表的每一行(即假设 TextView 在我将显示更新值的每一行内)?

I am trying to update the ListView with timer. I have implemented the android UI timer but my problem is how to use it for ListView where I need to update each row of the list after a certain interval. How does the handler will update the each row of the list (i.e. suppose a TextView is inside the each row where I'll display the updated values)?

public class ListAdapter extends BaseAdapter {

    private List<String> messages;
    private Context mContext;

    public ListAdapter(Context context , List<String> messages){
        this.messages   =  messages;
        mContext   =  context;
    }

    @Override
    public int getCount(){
        return messages.size();
    }

    @Override
    public Object getItem(int location){
        return messages.get(location);
    }

    @Override
    public long getItemId(int index){
        return index;
    }

    @Override
    public View getView(int index , View convertView, ViewGroup viewGroup){

            TextView time = new TextView(mContext);

                //udpate the time.setText() using timer
        convertView = (View)time

        return convertView;
    }   

推荐答案

创建一个customHandler类,扩展Handler类,并从timer run()方法中调用handler的sendEmptyMessage().

Create a customHandler class that extends Handler class and call the sendEmptyMessage() of handler from the timer run() method.

在 Handler 类中覆盖 handleMessage 并更新您的列表视图值并调用 adapter.notifyDataSetChanged() 这将使用更新后的值刷新列表视图.

In the Handler class override the handleMessage and update your listview values and call adapter.notifyDataSetChanged() which will refresh the listview with the updated values.

这是示例代码:

Timer timer = new Timer();
CustomTimerTask customTimerTask = new CustomTimerTask();
customTimerTask.run();
timer.scheduleAtFixedRate(customTimerTask, 1000 , 1000);

class CustomTimerTask extends TimerTask {

    @Override
    public void run() {
        myHandler.sendEmptyMessage(0);
    }
}

    class CustomHandler extends Handler{


    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        /// Do your listview update thing
 }

}

这篇关于使用计时器更新列表 UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆