我尝试制作两个按钮,这些按钮会在点击时更改一个值的加减1,并且在按住按钮时每秒不断加1或减1次。当点击按钮或按住按钮时,我可以获得要更改的值,但我无法获得我想要的行为。这就是我所拥有的:
btPlus.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
setTempo(mTempo + 1);
mTempo=mTempo+1;
tvTempo.setText(Integer.toString(mTempo));
return true;
}
return false;
}
});
btMinus.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
setTempo(mTempo - 1);
mTempo=mTempo-1;
tvTempo.setText(Integer.toString(mTempo));
return true;
}
return false;
}
});
btPlus.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
int action = motionEvent.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (getActivity() == null)
return;
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
tvTempo.setText(Integer.toString(mTempo));
mTempo++;
if (mTempo > 300)
mTempo = 300;
}
});
}
}, 100, 100);
break;
case MotionEvent.ACTION_UP:
timer.cancel();
}
return true;
}
});
btMinus.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
int action = motionEvent.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (getActivity() == null)
return;
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
tvTempo.setText(Integer.toString(mTempo));
mTempo--;
if (mTempo < 1)
mTempo = 1;
}
});
}
}, 100, 100);
break;
case MotionEvent.ACTION_UP:
timer.cancel();
}
return true;
}
});
return rootView;
}
感谢您的帮助!
答案 0 :(得分:0)
您可以实施onKeyListener
来确定按钮的保留时间,例如:
或使用onLongClickListener
执行与常规&#34;点击&#34;的不同功能像这里: