1

我是 Android 新手,只是尝试逐帧开始动画,每个帧图像都正确缩放。我从类型化数组资源中获取帧,然后将它们添加到 AnimationDrawable 对象。看起来帧已成功添加,但动画未在模拟器中启动 - 发生异常并返回 null。这是我的代码。

SecondActivity.java

package mypackage;

import android.app.Activity;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.Toast;


public class SecondActivity extends Activity {


    AnimationDrawable xAnimation;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        ImageView vImage = (ImageView) findViewById(R.id.imageView1);
        Resources res = getResources();
        TypedArray pics_Res = res.obtainTypedArray(R.array.pics_res);
        AnimationDrawable xAnimation = new AnimationDrawable();
        xAnimation.setOneShot(false);
        Drawable Mypic;

        try {
        for(int i = 1; i<4; i++)
        {

            Mypic = pics_Res.getDrawable(i);
            vImage.setImageDrawable(Mypic);
            vImage.setAdjustViewBounds(true);
            xAnimation.addFrame(vImage.getDrawable(), 2000);
            Mypic = null;

        }


        }
        catch (Exception e){
            Log.e("activity_second", "exception occured = " + e.getMessage());
        }
        finally{
            /*System.exit(1);*/ 
        }
    }


      public void onWindowFocusChanged(boolean hasFocus) {

        super.onWindowFocusChanged(hasFocus);

      if(hasFocus) 
          try {
              Log.e("second_activity", "animation started");

              if (xAnimation != null) {
                  xAnimation.start();
              }
              else
              Log.e("second_activity", "animation is null");
          }
          catch (Exception e){
            Log.e("activity_second", "exception occured = " + e.getMessage());
          }
          finally{
              /*System.exit(1); */
          }
      }

res\values\arrays.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <array name="pics_res">
        <item>@drawable/pic1</item>
        <item>@drawable/pic2</item>
        <item>@drawable/pic3</item>
        <item>@drawable/pic4</item>
        <item>@drawable/pic5</item>
    </array>

</resources>

布局\activity_second.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >


<ImageView
    android:id="@+id/imageView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"

/>

</LinearLayout>
4

0 回答 0