我正在尝试创建一个按钮,当按钮被释放时,该按钮会向其添加1或任何数字。我的目标是创建一个屏幕上的光标键控制器来移动按钮/位图。以下代码仅在按下时添加1。如何让它连续计算?
谢谢你的帮助
package s.apps.kontroler;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;
public class Test extends Activity implements OnTouchListener {
Button up;
TextView text;
int countup;
boolean isDown = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
up = (Button) findViewById(R.id.button1);
text = (TextView) findViewById(R.id.textView1);
up.setOnTouchListener(this);
}
public boolean onTouch(View arg0, MotionEvent event) {
// TODO Auto-generated method stub
int i = event.getAction();
if (i == MotionEvent.ACTION_DOWN) {
isDown = true;
if (isDown) {
countup++;
text.setText("Count is: " + countup);
}
else if (i == MotionEvent.ACTION_UP) {
isDown = false;
}
}
return true;
}
}
答案 0 :(得分:5)
这应该这样做:
private static final int INTERVAL=500;
private Handler handler= new Handler();
private Runnable incrementRunnable = new Runnable() {
@Override
public void run() {
countup++;
text.setText("Count is: " + countup);
handler.postDelayed(this, INTERVAL);
}
}
public boolean onTouch(View arg0, MotionEvent event) {
int i = event.getAction();
if (i == MotionEvent.ACTION_DOWN) {
incrementRunnable.run();
}
else if (i == MotionEvent.ACTION_UP) {
handler.removeCallbacks(incrementRunnable);
}
return true;
}
答案 1 :(得分:2)
怎么样,
Calendar c = Calendar.getInstance();
int i = c.get(Calendar.SECOND);
While(//button is held )
{if(c.get(Calender.SECOND)>i)
i++;//addto variable}