1.layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_gravity="center_horizontal"
android:layout_width="200dp"
android:layout_height="200dp"
android:id="@+id/imag" />
<Button
android:layout_marginTop="20sp"
android:layout_gravity="center"
android:id="@+id/next"
android:text="下一张"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
2.java
public class MainActivity extends AppCompatActivity {
String[] images = null;
AssetManager assets = null;
int currentImg = 0;
ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*Bitmap b = new Bitmap();
BitmapDrawable bd = new BitmapDrawable(b);
Bitmap a = bd.getBitmap();*/
image = (ImageView) findViewById(R.id.imag);
try{
assets = getAssets();
images = assets.list("");//参数为文件夹的名字,空就是所有文件.返回指定路径下的所有文件及目录名string数组
} catch (Exception e){
Log.i("mydate" , "错误1");
}
Button next = (Button) findViewById(R.id.next);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (currentImg >= images.length){
currentImg = 0;
}
//找下一张图片
while(!images[currentImg].endsWith(".png") && !images[currentImg].endsWith(".jpg") && !images[currentImg].endsWith(".gif")) {
currentImg ++; //过滤掉不为图片的
if (currentImg >= images.length){
currentImg = 0;
}
}
InputStream assetFile = null;
try{
//assets下的文件只能读(用open打开inputsream),不能写
assetFile = assets.open(images[currentImg++]);
} catch (Exception e){
Log.i("mydate" , "错误2");
}
//得到image的图片
BitmapDrawable bitmapDrawable = (BitmapDrawable) image.getDrawable();
//先回收之前那张图片
if (bitmapDrawable != null && !bitmapDrawable.getBitmap().isRecycled()){
bitmapDrawable.getBitmap().recycle();
}
//设置新的图片
image.setImageBitmap(BitmapFactory.decodeStream(assetFile)); //将assets目录下的图片给image
}
});
3.assets中的文件列表