I want to apply fade in/out effect on an ImageView via AnimationListener from the separate thread. The following piece of code is working, if it's called from the main thread:
public static void setImage(final ImageView imageView, final int image)
{
final Animation fadeIn = new AlphaAnimation(0, 1);
fadeIn.setInterpolator(new DecelerateInterpolator());
fadeIn.setDuration(2000);
final Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setInterpolator(new AccelerateInterpolator());
fadeOut.setDuration(2000);
AnimationSet animation = new AnimationSet(false);
animation.addAnimation(fadeOut);
animation.setRepeatCount(1);
imageView.setAnimation(animation);
animation.setAnimationListener(new Animation.AnimationListener()
{
public void onAnimationEnd(Animation animation)
{
// TODO Auto-generated method stub
imageView.setImageResource(image);
imageView.startAnimation(fadeIn);
}
public void onAnimationRepeat(Animation animation)
{
// TODO Auto-generated method stub
}
public void onAnimationStart(Animation animation)
{
// TODO Auto-generated method stub
}
});
}
Somewhere in MainActivity:
protected void onCreate(Bundle savedInstanceState)
{
...
Animator.setImage(imageView, R.drawable.ic_check_circle);
...
}
However, it doesn't seem to work properly if executed inside asynctask:
private class JSONParse extends AsyncTask<String, String, JSONObject>
{
private ProgressDialog pDialog;
@Override
protected void onPreExecute()
{
super.onPreExecute();
}
@Override
protected JSONObject doInBackground(String... args)
{
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(ins_url);
return json;
}
@Override
protected void onPostExecute(JSONObject json)
{
try
{
if( json.getString( "status" ).equals( "true" ) )
{
System.out.println("Ok!");
// Nothing happens when setImage method is invoked
Animator.setImage(imageView, R.drawable.ic_check_circle);
// setImageResource works fine
// imageView.setImageResource(R.drawable.ic_check_circle);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
I came up with an idea to run it in the main thread, but failed to make it work either:
Handler mainHandler = new Handler(getBaseContext().getMainLooper());
Runnable r = new Runnable()
{
@Override
public void run() {
Animator.setImage(imageView, R.drawable.ic_check_circle);
}
};
mainHandler.post(r);
Any suggestions?