Here is the code for the OnTouchListener:
launchableSelectionView.setOnTouchListener(new View.OnTouchListener()
{
final CountDownTimer countDownTimer = new CountDownTimer(Long.MAX_VALUE,100)
{
@Override
public void onTick(long l)
{
MissileSystem system = bFittedToPlayer ? game.GetOurPlayer().GetInterceptorSystem() : game.GetSAMSite(lFittedToStructureID).GetInterceptorSystem();
int lFreeSlots = system.GetEmptySlotCount() - Types.size();
int lAvailableFunds = game.GetOurPlayer().GetWealth() - lTotalCost;
if (lFreeSlots == 0)
{
activity.ShowBasicOKDialog(context.getString(R.string.insufficient_slots));
}
else if (lAvailableFunds < game.GetConfig().GetInterceptorCost(type))
{
activity.ShowBasicOKDialog(context.getString(R.string.insufficient_funds));
}
else
{
launchableSelectionView.IncrementNumber();
AddType(type.GetID());
}
}
@Override
public void onFinish()
{
}
};
@Override
public boolean onTouch(View view, MotionEvent motionEvent)
{
if (motionEvent.getAction() == MotionEvent.ACTION_DOWN)
{
postDelayed(new Runnable()
{
@Override
public void run()
{
countDownTimer.start();
}
}, 750);
}
if (motionEvent.getAction() == MotionEvent.ACTION_UP)
{
countDownTimer.cancel();
}
return false;
}
});
This code is for players to purchase missiles.
What I want it to do is increment the number of missiles to purchase when the user long-presses the button after .75 seconds, and cease incrementing the number when the player lifts their finger.
What it does instead: If the user taps the button, it will wait .75 seconds and then begin incrementing the number as though the user were still touching the button. (Before I added PostDelayed, it would begin incrementing the number immediately, and not stop.)
CodePudding user response:
I would be using a android.os.Handler
to intercept the java.lang.Runnable
before it can ever run. After that, ditch the CountDownTimer
altogether.
//Recreate a Handler over and over again.
Handler hand=new Handler();
Runnable run=new Runnable(){
@Override
public void run(){
MissileSystem system = bFittedToPlayer ? game.GetOurPlayer().GetInterceptorSystem() : game.GetSAMSite(lFittedToStructureID).GetInterceptorSystem();
int lFreeSlots = system.GetEmptySlotCount() - Types.size();
int lAvailableFunds = game.GetOurPlayer().GetWealth() - lTotalCost;
if (lFreeSlots == 0)
{
activity.ShowBasicOKDialog(context.getString(R.string.insufficient_slots));
}
else if (lAvailableFunds < game.GetConfig().GetInterceptorCost(type))
{
activity.ShowBasicOKDialog(context.getString(R.string.insufficient_funds));
}
else
{
launchableSelectionView.IncrementNumber();
AddType(type.GetID());
//Increment every 1ms
hand.postDelayed(this, 1);
}};
hand.postDelayed(run, 750);
//To intercept if user just didn't held on long enough.
hand.removeCallbacks(run);