Reputation: 211
I am trying to set a button state to pressed=true onTouch, and then have it set back to pressed=false after a certain time period.
The onTouch method properly sets the state to pressed
myTouchListener= new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
lastPressed = (Button)v;
lastPressed.setPressed(true);
return true;
}
};
I then thought I could use a timer to set it back to original state. But a timer takes a TimerTask, which takes a runnable, so I can not pass it a reference to "lastPressed" button.
I am completely at a loss as where to go from here.
Upvotes: 1
Views: 412
Reputation: 4165
Its actually really easy,
create a final variable pointing to the same button, then you can use it in a thread,
and so start a new thread, which sets it false after a period of time:
myTouchListener= new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
lastPressed = (Button)v;
lastPressed.setPressed(true);
final Button lp = lastPressed;
Thread t = new Thread()
{
public void run()
{
try
{
Thread.sleep(1000); //your time in milliseconds here
} catch (Exception e) { }
lp.setPressed(false);
}
}
t.start();
return true;
}
};
Upvotes: 1
Reputation: 784
Try to control the states of your button with onTouchEvent.
This is sample code:
button.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// show interest in events resulting from ACTION_DOWN
if(event.getAction()==MotionEvent.ACTION_DOWN) return true;
// don't handle event unless its ACTION_UP so "doSomething()" only runs once.
if(event.getAction()!=MotionEvent.ACTION_UP) return false;
doSomething();
button.setPressed(true);
return true;
}
});
Upvotes: 0
Reputation: 5411
Use a message handler, and send a message from the timer task back to your activity, when the button state should be reset.
Note: The actual timing of TimerTask is known to be too inaccurate for many applications.
A better way, without using a TimerTask, would be to set up a message handler in your activity. Then after setting the button state to pressed, your activity can post a delayed message to itself to re-set the button state at the desired future time.
Upvotes: 0