如何在动画结束删除视图?视图、结束、动画、如何在

2023-09-12 11:31:11 作者:红唇的诱惑

我要创建一个游戏,我想显示一个简单的分数 - 动画的播放器时信用是送给他。这是我扔在屏幕上的看法:

I'm creating a game and I would like to display a simple "score"-animation to the player when credits are given to him. This is the view I throw onto the screen:

public class Score extends FrameLayout {

  public Score(Context context, int score) {
    super(context);
    TextView txt = new TextView(context);
    txt.setText(String.valueOf(score).toUpperCase());  
    addView(txt);
    Animation anim = AnimationUtils.loadAnimation(context, R.anim.score);
    startAnimation(anim);
    anim.setAnimationListener(animationListener);
  }
  private void Remove(){

    ViewGroup parent = (ViewGroup)getParent();  
    parent.removeView(this);

  } 
  private AnimationListener animationListener = new AnimationListener() {

    @Override
    public void onAnimationEnd(Animation animation) {

      Remove();
    }  
  };
}

这code的实际工作pretty的同时,只要有只有一个得分的动画在屏幕上,在任何给定的时间。如果玩家再次得分,最后的比分被删除之前,应用程序崩溃 - 可能是因为第二个得分得到了事件动画过程中删除自己。这是用动画的一种不好的做法?如何将你们处理呢?

This code actually works pretty well as long as there is only ONE score animation on screen at any given time. If the player scores again, before the last score was removed, the app crashes - probably because the second score gets the event to remove itself during animation.. Is this a bad practice of using Animation? How would you guys handle this?

推荐答案

我还发现,应用动画这个观点(使用onAnimationEnd)后,除去从其父视图时崩溃与NPE父的dispatchDraw。

I also found that when removing a view from its parent after applying an animation to this view (using onAnimationEnd) crashes with NPE on the dispatchDraw of the parent.

我发现的唯一的解决办法是触发后调用中删除。正常情况下所有的用户界面的修改必须完成的UI线程,所以我说的活性runOnUiThread通话,但它可能是无用的(它的工作对我来说没有这个功能)。

The only solution I found is to trigger the removal inside a post call. Normally all UI modification must be done on the UI thread, so I added a runOnUiThread call on the activity, but it could be useless (it works for me without that).

Animation animation = AnimationUtils.loadAnimation(parentView.getContext(), animationId);
animation.setAnimationListener(new AnimationListener() {
    public void onAnimationStart(Animation paramAnimation) { }
    public void onAnimationRepeat(Animation paramAnimation) { }
    public void onAnimationEnd(Animation paramAnimation) { 
        // without the post method, the main UI crashes if the view is removed 
        parentView.post(new Runnable() {
            public void run() {
                // it works without the runOnUiThread, but all UI updates must 
                // be done on the UI thread
                activity.runOnUiThread(new Runnable() {
                    public void run() {
                        parentView.removeView(view);
                    }
                });
            }
        });
    }
});

view.setVisibility(visibility());
view.startAnimation(animation);
 
精彩推荐
图片推荐