本文介绍了将progressBar与Handler同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将处理程序与progressBar链接?

How can I link a handler with a progressBar?

fun start() {
    started = true
    handler.postDelayed(runnable, 13000)
}


private val runnable = Runnable {
    start()
}

推荐答案

还有其他解决方案,但我更喜欢:

There are some other solution but I prefer this:

final static int TH_MESSAGE_START = 0;
final static int TH_MESSAGE_PROGRESSION = 1;
final static int TH_MESSAGE_END = 2;

final ProgressBar mProgressBar = .....

final static Handler mHandler = new Handler(Looper.getMainLooper()) {
   @Override
   public void handleMessage(@NonNull final Message) {
      switch (message.what) {
         case TH_MESSAGE_START:
            mProgressBar.setProgress(0);
            break;
         case TH_MESSAGE_PROGRESSION:
            mProgressBar.setProgress(message.arg1);
            break;
         case TH_MESSAGE_END:
            mProgressBar.setProgress(mProgressBar.getMax());
            break;
      }
   }
};

private static boolean postToMainThread(final int what, final int arg1) {
   if (mHandler == null) return false;
   final Message cMessage = new Message();
   cMessage.what = what;
   cMessage.arg1 = arg1;
   return mHandler.sendMessage(cMessage);
}
private static boolean postToMainThread_progressBarStart() {
   return postToMainThread(TH_MESSAGE_START, 0);
}
private static boolean postToMainThread_progressBarProgress(final int progression) {
   return postToMainThread(TH_MESSAGE_PROGRESSION, progression);
}
private static postToMainThread_progressBarEnd() {
   return postToMainThread(TH_MESSAGE_END, 0);
}

然后,您可以从任何线程中调用这些postToMainThread_xxxx()方法来同步"mProgressBar".

Then from ANY THREAD you could call those postToMainThread_xxxx() methods to sync your "mProgressBar".

(我知道其中两个TH_MESSAGE没有用,但是用户可能想在开始和结束时做不同的事情)

这篇关于将progressBar与Handler同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 19:28