可绘制动画不起作用

drawable animation not workin

我想在我的列表中使用可绘制动画,但是当我启动 listActivity 时它崩溃了 我从 this 中学到了 ,当我删除这 2 个动画代码时

 AnimationDrawable frameAnimation = (AnimationDrawable) GamePic.getBackground();
        frameAnimation.start();

,它在我的 phone(p7 with android 4.4)中自行动画,但在其他 phones 中我已经尝试过(asus memopad 7,sony c)它与没有动画绘图!注意,当我使用这个向上代码时,所有 phone 都会崩溃 下面是我的完整代码,有什么问题吗?

public class MyList extends ListActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.games_list);

    setListAdapter(new AA());
}


@Override
protected void onListItemClick(ListView l, View v, int position, long id) {

    Toast.makeText(MyList.this, "item" + position + "is clicked", Toast.LENGTH_SHORT).show();

}


class AA extends ArrayAdapter<String> {

    public AA() {
        super(MyList.this, R.layout.games_list_layout, Resources2.GameListArray);
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View row = convertView;
        if (row == null) {
            LayoutInflater inflater = getLayoutInflater();
            row = inflater.inflate(R.layout.games_list_layout, parent, false);
        }
        TextView GameName = (TextView) row.findViewById(R.id.textView1);
        ImageView GamePic = (ImageView) row.findViewById(R.id.imageView2);
        ImageView Cartridge = (ImageView) row.findViewById(R.id.imageView1);

        GameName.setText(Resources2.GameListArray[position]);
        GamePic.setImageResource(Resources2.GamePicArray[position]);
        Cartridge.setImageResource(Resources2.CartridgeFrame[Resources2.cartridgeColor[position]]);

        AnimationDrawable frameAnimation = (AnimationDrawable) GamePic.getBackground();
        frameAnimation.start();

        return row;

    }
}

}

谢谢

documentation 所述,您应该等到 View 附加到 window 后再开始动画。因此,您应该将 OnAttachStateChangeListener 添加到将在附加时执行的视图,并从那里开始动画。

ImageView img = (ImageView)v.findViewById(R.id.image);
img.setBackgroundResource(R.drawable.anim);
img.addOnAttachStateChangeListener(new  View.OnAttachStateChangeListener() {
  @Override
  public void onViewAttachedToWindow(View v) {
  AnimationDrawable animation = (AnimationDrawable) v.getBackground();
  animation .start();
  }

@Override
public void onViewDetachedFromWindow(View v) {
}
});

或者如果您使用的是 GIF,请使用电影 Class。这里有一些学习链接,this , this and this also this quistion

我找到我的问题了!

我用过 GamePic.setImageResource(Resources2.GamePicArray[位置]);

但我应该使用

GamePic.setBackgroundResource(Resources2.GamePicArray[position]);

现在可以正常使用了!