Pra*_*ker 2 android button postdelayed motionevent
我想要的是:用户将按钮保持点击 1900 毫秒。如果他在 1900 毫秒之前拿起手指,手机就会停止振动。而如果他将手指放在按钮上超过 1900 秒,calculate()方法就会运行。 我正在使用:postDelayed,因为我阅读它不会干扰 ui 线程。我试图检查 1900 秒是否已经过去,用户还没有选择他的手指,甚至比计算方法运行还要好。 发生错误:如果用户在 1900 秒之前拿起他的手指或只是他触摸并立即拿起,手机会一直振动。虽然它不应该发生,因为我正在使用 MotionEvent.ACTION_UP 检查它。请帮忙 !!
int flag = 0;
int aborted_flag = 0;
@Override
public boolean onTouch(View v, MotionEvent event) {
Handler mHandler = new Handler();
if(event.getAction()==MotionEvent.ACTION_DOWN){
scanning();
t1 = System.currentTimeMillis();
vibrator.vibrate(1900);
mHandler.postDelayed(new Runnable() {
public void run() {
check();
}
}, 1901);
}
if(event.getAction()==MotionEvent.ACTION_UP){
if(flag == 0){
t2 = System.currentTimeMillis();
vibrator.cancel();
calculate();
aborted_flag = 1;
}
}
return true;
}
private void check() {
t2 = System.currentTimeMillis();
Log.e("Hello","Inside Check");
Log.e("Hello",""+aborted_flag);
vibrator.cancel();
if(aborted_flag==0){
calculate();
flag = 1;
}
}
private void scanning() {
textView.setText("Scanning");
}
private void calculate() {
Log.e("t2-t1 ", t2-t1+"");
if(t2-t1>=1900){
Random r = new Random();
int k = r.nextInt((5 - 0) + 1) + 0;
textView.setText(str[k]);
////////////animation library code/////////////
YoYo.with(Techniques.StandUp)
.duration(700)
.playOn(findViewById(R.id.text_view));
////////////////////////////////////////
changeBackgroundColor(k);
//textView.setTextColor(Color.parseColor("#00ff00"));
flag = 0;
}
else{
textView.setText("Aborted\n Try Again");
relativeLayout.setBackgroundResource(R.color.red);
}
}
public void changeBackgroundColor(final int k) {
runOnUiThread(new Runnable(){
public void run() {
switch(k){
case 0: relativeLayout.setBackgroundResource(R.color.blue);
break;
case 1: relativeLayout.setBackgroundResource(R.color.pink);
break;
case 2:;
case 3: relativeLayout.setBackgroundResource(R.color.green);
break;
default:relativeLayout.setBackgroundResource(R.color.yellow);
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
如果您postDelayed从 UI 线程调用,那么您的代码将在 UI 线程上执行。
要使用不同的线程创建一个:
Thread t = new Thread(new Runnable(){});
t.start();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5559 次 |
| 最近记录: |