当前位置: 首页 > 工具软件 > View Animator > 使用案例 >

Android java.lang.IllegalStateException: Cannot start this animator on a detached view!

贺恩
2023-12-01
http://stackoverflow.com/questions/26475147/error-while-trying-to-create-circular-reveal-illegalstateexception-cannot-star

So, I'm experimenting trying to create a circular reveal on API level 21 on a TextView but I keep getting this error. At first I thought it had something to do with the lifecycle of the fragment I was attempting it but then I just tried the same thing in an activity and it still wouldn't work.
Here's the code:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window w = getWindow();
        w.setFlags(
                WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS,
                WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        w.setStatusBarColor(Color.parseColor("#0277bd"));


        setContentView(R.layout.activity_main);


        TextView tv = (TextView) findViewById(R.id.text);



        int a = (tv.getLeft() + tv.getRight()) / 2;
        int b = (tv.getTop() + tv.getBottom()) / 2;

        int radius = tv.getWidth();

        Animator anim = ViewAnimationUtils.createCircularReveal(tv, a, b, 0, radius);

        anim.start();





    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        return super.onCreateOptionsMenu(menu);
    }
}

It's still early days so I can't really find any answers about this. Any ideas?

 

1.
You can use Runnable to do the animation. The Runnable will run after the view's creation. No need to post delay.

view.post(new Runnable()
{ 
       @Override 
       public void run(){ 
           //create your anim here
       } 
});

2.
Or you can do this.
 tv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                tv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            } else {
                tv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
            Animator anim = ViewAnimationUtils.createCircularReveal(tv, a, b, 0, radius);
            anim.start();
        }
    });

Adding GlobalLayoutListener to wait for the view to be inflated worked for me.

3.
Or you can do this.
tv.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        //start your animation here                        
                    }
                }, 1000);


4.
Or you can do this.

Call your Animator logic from onResume(). That way you'll be sure all views have been attached in the layout.

 类似资料:

相关阅读

相关文章

相关问答