首页 > 解决方案 > 更快地启动对象并更快地更新 Textview

问题描述

我想创建多个计时器。我ArrayListMainActivity. 然后将它们添加到 a 中ReyclerView,以便它们也被显示。首先,我通过一个 for 循环并startTimer ()为每个单独的对象执行该方法。不幸的是,并非每个计时器的时间都是正确的。这意味着一个计时器更快,第二个更慢,依此类推。所以每个计时器在不同的时间开始,或者文本在不同的时间改变。

我现在的问题是,是否有其他方法可以启动计时器并更改 TextView 中的文本,以便 GUI 更新得更快并且程序本身运行得更快?目标应该是所有计时器都同样快并且没有延迟。提前致谢。期待解答!

主要活动

     timerList= new ArrayList<>();
        for (int i = 1; i <= 10; i++) {
            timerList.add(new Timer(i, 600000 * i))); // 
Each timer has a different time
        }
    
        recyclerView.setLayoutManager(recyclerViewLayoutManager);
        adapter = new TimerAdapter(this, timerList);
    
        recyclerView.setAdapter(adapter);
        context = this;
    
    
        button_start.setOnClickListener(v -> {
    
                for (Timer timer: timerList) {
                    timer.startTimer();
                
    
        });
    
    @Override
    public void updateMyText(int index, long time) {
        timerList.get(index-1).setTime(time);
        adapter.notifyDataSetChanged();
    }

定时器

public interface MyCallback {
    public void updateMyText(int index, long time);
}
   public Timer(int index, long startTimeMilliseconds) {
        this.index = index;
        this.time = startTimeMilliseconds;
        mTimeLeftInMillis = startTimeMilliseconds;
        startTime = startTimeMilliseconds;
    }



    public void startTimer() {
        mCountDownTimer = new CountDownTimer(mTimeLeftInMillis, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mTimeLeftInMillis = millisUntilFinished;
                updateCountDownText();
            }
            @Override
            public void onFinish() {
                mTimerRunning = false;
            }
        }.start();
        mTimerRunning = true;
    }

    public void resetTimer() {
        mCountDownTimer.cancel();
        mTimerRunning = false;
        mTimeLeftInMillis = startTime;
        timeLeftFormatted = formattedTime(startTime);
        changeText(index-1);
    }

    public void updateCountDownText() {
        //MainActivity.timerList.get(getIndex()-1).setTime(mTimeLeftInMillis);
        //MainActivity.adapter.notifyDataSetChanged();
        if(myCallback != null) {
            myCallback.updateMyText(getIndex(), mTimeLeftInMillis);
        }
    }

标签: javaandroidtimer

解决方案


使用实时数据和绑定或 MVVM 设计模式。您不必担心视图的更快更新操作。


推荐阅读