Reputation: 2626
I am writing an app, where one of my views need to blink by the use of a timer constantly, but I have trouble with making it blink.
Here's my handler code
@SuppressWarnings("All")
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
try {
circle.setVisibility(View.VISIBLE);
Thread.sleep(100);
circle.setVisibility(View.INVISIBLE);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
So i am sending an empty message to the handler with some INTERVAL
constantly, and I want the image to get visible for 100 milliseconds and then hide again. But the problem is, until the method is finished, my UI elements won't get refreshed. How I do this?
Thanks in advance.
Upvotes: 0
Views: 76
Reputation: 518
An alternative to the above solutions (Handler
, Thread
...) is to create an Animator
and rely on Androids flexible animation capabilities.
In this code-snippet you animate directly on the visibility-property of your View
, whereas you need to define a custom TimeInterpolator
(which only return two distinct values 0.0 and 1.0) as shown:
final ObjectAnimator anim = ObjectAnimator.ofInt(circle, "visibility",
View.VISIBLE, View.INVISIBLE);
anim.setRepeatMode(Animation.REVERSE);
anim.setRepeatCount(Animation.INFINITE);
anim.setDuration(1000);
anim.setInterpolator(new TimeInterpolator() {
@Override
public float getInterpolation(float input) {
return Math.round(input);
}
});
anim.start();
Upvotes: 0
Reputation: 91
Thread t = new Thread() {
@Override
public void run() {
try {
while (!isInterrupted()) {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
@Override
public void run() {
if(circle.isVisible()){circle.setVisibility(View.VISIBLE);}
else{
circle.setVisibility(View.INVISIBLE);
}
}
});
}
} catch (InterruptedException e) {
}
}
};
t.start();
Upvotes: 1
Reputation: 10177
Here's an example of runnable that toggles visibility and infinitely reposts itself, delayed every 100 miliseconds. The problem that you are having is you are stopping the main UI thread, so nothing else is going to happen and your program is probably freezing right? Anyways, this is one style of solution. Another might be to do the posting in another thread.
final Handler mHandler = new Handler();
final View circle = ....;
Runnable blink = new Runnable() {
@Override
public void run() {
int vis = circle.getVisibility();
if(vis == View.VISIBLE){
circle.setVisibility(View.INVISIBLE);
}else{
circle.setVisibility(View.VISIBLE);
}
mHandler.postDelayed(this, 100);
}
};
mHandler.post(blink);
Upvotes: 0
Reputation: 3311
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
if(msg.what == 1) circle.setVisibility(View.VISIBLE);
if(msg.what == 2) circle.setVisibility(View.INVISIBLE);
}
};
then send message 1 & 2 somewhere.
Upvotes: 0