AssetManager reads multiple picture resources under assets and outputs them to ImageView animation

Keywords: Android Java

AssetManager reads multiple picture resources under assets and outputs them to ImageView animation

There are several key points and links to note:
1. AssetManager reads the original image resource file placed in the assets directory in advance and assembles it into the Bitmap array of Android.
The file structure is shown in the figure:

2. Set the Bitmap array read from 1 to ImageView every other small time (such as 25ms), so as to form a visual animation effect.

Code:

package zhangphil.test;

import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;

import java.io.InputStream;
import java.util.concurrent.TimeUnit;

public class AnimationActivity extends AppCompatActivity {
    private boolean mStartLoadingAnimation = false;
    private ImageView mImageView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.animation_activity);
        mImageView = findViewById(R.id.image);

        mStartLoadingAnimation = true;
        loadingAnimation();
    }

    private void loadingAnimation() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Bitmap[] bitmaps = getBimaps();
                if (bitmaps == null || bitmaps.length == 0) {
                    return;
                }

                int i = 0;
                while (mStartLoadingAnimation) {
                    mImageView.setImageBitmap(bitmaps[i++ % bitmaps.length]);

                    try {
                        TimeUnit.MILLISECONDS.sleep(25);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    private Bitmap[] getBimaps() {
        final String parentPath = "loading";

        Bitmap[] bitmaps = null;
        AssetManager am = getAssets();
        try {
            String[] files = am.list(parentPath);
            bitmaps = new Bitmap[files.length];
            for (int i = 0; i < files.length; i++) {
                InputStream is = am.open(parentPath + "/" + files[i]);
                bitmaps[i] = BitmapFactory.decodeStream(is);
                is.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bitmaps;
    }
}

 

Posted by TheDeadPool on Tue, 31 Dec 2019 21:39:39 -0800