0

加载 ListView 时我需要一个计时器。喜欢“等待 [(Timer) 42] 秒购买元素”我想向用户显示 Textview 喜欢它。我不能在 ListView 中使用线程...

我从 runOnUiThread 得到错误。为什么 ?我不能在 Listview 中使用计时器。

 @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        final TextView LblTime;

        inflater=(LayoutInflater)Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view=inflater.inflate(R.layout.test,parent,false);

        LblTime=(TextView)view.findViewById(R.id.LblFragmentAnaListViewKalanSure );

       Timer T=new Timer();
        T.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                Context.getApplicationContext().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        long Time= MyTime.get(position).getTime() - (new Date()).getTime();
                        long Sec= Time/ 1000 % 60;
                        long Min= Time/ (60 * 1000) % 60;
   LblTime.setText(Min+":"+Sec);
                    }
                });
            }
        }, 1000, 1000);
        return view;
    }
4

3 回答 3

2

试试这个.. for call atfer 42 sec..

(new Handler()).postDelayed(new Runnable() {

    public void run() {
        // do you want
     }
 }, 42000);

如果每一秒你都需要这样做..

这是使用处理程序

初始化..

Handler handler = new Handler();

进口

import android.os.Handler;

打电话给..

 handler.postDelayed(yourtask,42*1000);



 private Runnable yourtask = new Runnable() {
    public void run() {

      // Run your code..
        handler.removeCallbacks(yourtask);
        handler.postDelayed(yourtask, 42*1000); // again start...

    }
};

这是每隔一秒使用一次计时器......

final Handler handler = new Handler();
Timer timer = new Timer();
private int DELAY = 1000 * 60 * 1;

叫这个

   timer.scheduleAtFixedRate(doAsynchronousTask, 0, DELAY);

在班上

  TimerTask doAsynchronousTask = new TimerTask() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
             // your code


                }

            });


        }
    };
于 2016-08-22T10:33:25.250 回答
1

而不是计时器尝试使用 CountDownTimer

new CountDownTimer(10000, 20000) {
        @Override
        public void onTick(long millisUntilFinished) {}

        public void onFinish() {
        }
    }.start();
于 2016-08-22T10:15:55.333 回答
1

Try to use CountDownTimer it works perfectly in UI thread. All you need is just to initiate it in your code like that:

timer = new CountDownTimer(MS_TILL_COMPLETE, TICK_OFFSET) {
        @Override
        public void onTick(long l) {
            //Repeating every TICK_OFFSET
        }

        @Override
        public void onFinish() {
            //Called after MS_TILL_COMPLETE
        }
    }.start();
于 2016-08-22T10:14:42.910 回答