我已设置ontouch侦听器为我的imagebutton实现一个计数器。但我只能检测被触摸和释放的按钮。只要按下按钮,我不确定如何实现递增,以及如何在释放按钮后停止递增。以下是我的代码:
up.setOnTouchListener(new OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction()==MotionEvent.ACTION_DOWN) {
pressdown();
}
else if (event.getAction()==MotionEvent.ACTION_UP) {
pressrelease();
}
return true;
}
答案 0 :(得分:1)
确定。这是我自己的问题的解决方案。它可能会帮助别人。
使用Handler对象,因为你必须实现一个单独的线程来递增/递减
public class MainActivity extends Activity{
private boolean autoIncrement = false;
private boolean autoDecrement = false;
private final long REPEAT_DELAY = 50;
private Handler repeatUpdateHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.input);
class RepetitiveUpdater implements Runnable{
@Override
public void run() {
if (autoIncrement) {
increment();
repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
}
else if(autoDecrement){
decrement();
repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
}
}
}
up.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
increment();
}
});
up.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
autoIncrement = true;
repeatUpdateHandler.post(new RepetitiveUpdater());
return false;
}
});
up.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction()==MotionEvent.ACTION_UP && autoIncrement ){
autoIncrement = false;
}
return false;
}
});
public void increment(){
if (i<100) {
i++;
TextView no = (TextView)findViewById(R.id.no);
no.setText(String.valueOf(i));
}
}
}
为减量做同样的事。
礼貌:Github,作者:Jeffrey F. Cole