更新 ProgressBar onTouch 并在发布时重新启动它(使用 imageButton)

Update ProgressBar onTouch and restart it on release (with imageButton)

我正在尝试实现以下目标 design/functionality:我有一个圆形图像,周围环绕着圆形进度条。我希望当用户触摸 imageButton 时,进度条会像这样开始它的进度:

问题是当用户决定从图像按钮 (MotionEvent.ACTION_UP) 上移开手指时,进度条不会停止并且 return 回到其初始状态 (0)。

这是我的代码:

public class MainActivity extends AppCompatActivity {
public CircleProgressBar progressBar;
private static final String TAG = MainActivity.class.getSimpleName();
private int totalProgressTime = 100;
Thread t;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    progressBar = (CircleProgressBar)findViewById(R.id.custom_progressBar);
    t = new Thread() {
        @Override
        public void run() {
            int jumpTime = 0;

            while(jumpTime < totalProgressTime) {
                try {
                    sleep(200);
                    jumpTime += 5;
                    final int finalJumpTime = jumpTime;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressBar.setProgress(finalJumpTime);
                        }
                    });
                }
                catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    };

    ImageButton imageButton = (ImageButton)findViewById(R.id.imageButton);
    imageButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_DOWN) {
                if(!t.isAlive()){
                    t.start();
                }else {
                    t.stop();
                }
                Toast.makeText(MainActivity.this, "onTouch", Toast.LENGTH_LONG).show();
            }

            if(event.getAction() == MotionEvent.ACTION_UP){
                t.interrupt();
            }

            Log.d(TAG, "Event type: " + event.toString());
            return false;
        }
    });

}

我认为您误解了如何使用线程。最重要的是,您不应该真正在 Android 中使用这样的线程。几乎不建议从 activity 开始一个线程(如果你来自 Java 背景并且正在学习 Android,那么很容易犯错误;我做了同样的事情)。另外,请阅读 Thread.stop 的 javadoc。您永远不应该调用该方法。

您可能想要做的是学习如何使用 Handler 以某个时间间隔在主线程上安排少量工作到 运行。继续安排新的位来执行您想要的渲染,直到有东西设置一个标志告诉它不再安排那个位。您根本不需要使用单独的线程就可以解决您的问题。