不使用notifyDataSetChanged更新ListView

有时候,我们在开发ListView的时候,可能item中只有一个控件要频繁刷新(1次/1秒),这时候,如果使用notifyDataSetChanged代价太大了,这就会导致我们在滑动ListView的时候出现卡顿。比如我们要实现如下界面效果的话,部分代码为:

private View view;
    private CurrentTask currentTask;
    private Handler timeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mlv_customed_task != null) {
                int size = mlv_customed_task.getChildCount();
                for (int i = 0; i < size; i++) {
                    view = mlv_customed_task.getChildAt(i);
                    currentTask = currentTasks.get(i);

                    TextView tv_day = (TextView) view.findViewById(R.id.tv_day);
                    TextView tv_hour = (TextView) view.findViewById(R.id.tv_hour);
                    TextView tv_minute = (TextView) view.findViewById(R.id.tv_minute);
                    TextView tv_second = (TextView) view.findViewById(R.id.tv_second);

                    String overTimestamp = currentTask.getOver_time();
                    if (!TextUtils.isEmpty(overTimestamp)) {
                        long over = Long.parseLong(overTimestamp);
                        long remainTimes = over - System.currentTimeMillis()/1000;
                        String[] date = DateTool.getOverTimeBySeconds(remainTimes);
                        tv_day.setText(String.format(mActivity.getResources().getString(R.string.current_task_day), date[0]));
                        tv_hour.setText(String.format(mActivity.getResources().getString(R.string.current_task_hour), date[1]));
                        tv_minute.setText(String.format(mActivity.getResources().getString(R.string.current_task_minute), date[2]));
                        tv_second.setText(String.format(mActivity.getResources().getString(R.string.current_task_second), date[3]));
                    }
                }
            }
        }
    };


    private ScheduledExecutorService timeExecutor = Executors.newScheduledThreadPool(3);
    private Runnable timeRunnable;

原理就是遍历ListView中的child,然后找到该child中对应的控件,进行刷新即可。

不使用notifyDataSetChanged更新ListView_第1张图片

你可能感兴趣的:(Android)