Android開發 利用imageview顯示選取的手機內存的圖片。activity_main.xml:
MainActivity.java文件:
package com.example.imageview; import java.io.File; import java.io.FileNotFoundException; import android.app.Activity; import android.content.ContentResolver; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends Activity { private Button selectImage; private ImageView imageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle("ImageView"); setContentView(R.layout.activity_main); selectImage = (Button) this.findViewById(R.id.selectImage); imageView = (ImageView) this.findViewById(R.id.imageView); selectImage.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO 自動生成的方法存根 Intent intent = new Intent(); //打開pictures畫面Type設置為image intent.setType("image/*"); //使用Intent.ACTION_GET_CONTENT 這個Action intent.setAction(Intent.ACTION_GET_CONTENT); //取得像片後返回本畫面 startActivityForResult(intent, 1); } }); } /** * 定義方法onActivityResult來處理用戶挑選的圖片。通過requestCode和resultCode返回標識碼,數據類型為Intent的data參數, * 調用Intent對象的getData()方法可以獲得具體內容。 */ protected void onActivityResult(int requestCode,int resultCode,Intent data){ if (resultCode==RESULT_OK){ Uri uri=data.getData(); ContentResolver cr=this.getContentResolver(); try{ Bitmap bitmap=BitmapFactory.decodeStream(cr.openInputStream(uri)); //將Bitmap設置到imageView imageView.setImageBitmap(bitmap); }catch(FileNotFoundException e) { e.printStackTrace(); } } super.onActivityResult(requestCode, resultCode, data); } }
在AndroidManifest.xml文件中添加權限: