讀取assets目錄下的圖片檔案
阿新 • • 發佈:2019-01-31
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 } });