开发者

Creating AnimationDrawable from assets

I locate several .png files (frames of my animation) in ass开发者_如何转开发ets folder, than I fetch them using AssetManager in my Activity's onCreate() method and fill my AnimationDrawable with them. As described in dev guide it's impossible to start Animation in onCreate() method and if I need to start it immediately than I should override onWindowFocusChanged() method. But even in such implementation my drawable object doesn't appears on the screen. Here is the code of my Activity:

package org.example.Animation;

import java.io.IOException;

import android.app.Activity;
import android.content.res.AssetManager;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class MainActivity extends Activity {
    private LinearLayout ll;
    private ImageView image;
    private AnimationDrawable ad;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ll = new LinearLayout(this);

        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(-2, -2);
        image = new ImageView(this);
        ll.addView(image, lp);
        setContentView(ll);


        AssetManager am = getAssets();
        ad = new AnimationDrawable();
        StringBuilder sb= new StringBuilder("loader/loader-");

        // Fetching frames from assets
        for(int i = 1; i < 11; i++) {
            sb.append(i);
            sb.append(".png");
            Log.d("DownloadImageTask", "Fetching image: " + sb.toString());         
            try {
                Drawable d = Drawable.createFromStream(am.open(sb.toString()), null);
                ad.addFrame(d, 500);                                        
            } 
            catch (IOException e) {
                Log.d("ImageViewAdapter", "IOException: " + e.getMessage());
            }
            sb.delete(14, sb.length()); // 14 - is the index of first digit of frame
        }

        image.setBackgroundDrawable(ad);                            
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {        
        super.onWindowFocusChanged(hasFocus);
        ad.start();
    }
} 

Tell me please what is wrong in my code?

P.S Please, don't ask me why I'm not using xml file. In shorts my main goal is to avoid uisng of R.java file.


Waiting for a long time, found solution myself thanks to this issue. Just need to change values of View's widht and height to fixed or to FILL_PARRENT


Frame by frame animation load from images in assets folder click here

Check this answer https://stackoverflow.com/a/45647381/2902830

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜