1.xml布局文件代码
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 tools:context=".DemoGetImage" > 6 <Button 7 android:id="@+id/mybutton" 8 android:layout_width="wrap_content" 9 android:layout_height="wrap_content" 10 android:layout_centerHorizontal="true" 11 android:text="选择图片"/> 12 13 <ImageView 14 android:id="@+id/myimageview" 15 android:layout_centerHorizontal="true" 16 android:layout_width="200dip" 17 android:layout_height="200dip" 18 android:scaleType="centerInside" 19 android:layout_below="@id/mybutton"/> 20 21 </RelativeLayout>
2Activity文件
package com.example.demogetimage; import java.io.FileNotFoundException; import android.net.Uri; import android.os.Bundle; import android.app.Activity; import android.content.ContentResolver; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.ImageView; public class DemoGetImage extends Activity { public Button mybutton = null; public ImageView myimageview = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_demo_get_image); mybutton = (Button)findViewById(R.id.mybutton); myimageview = (ImageView)findViewById(R.id.myimageview); mybutton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(intent.ACTION_GET_CONTENT); startActivityForResult(intent, 1); } }); } public void onActivityResult(int requestCode, int resultCode, Intent data){ if(RESULT_OK==resultCode){ Uri uri = data.getData(); ContentResolver cr = this.getContentResolver(); try { Bitmap bm = BitmapFactory.decodeStream(cr.openInputStream(uri)); myimageview.setImageBitmap(bm); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } super.onActivityResult(requestCode, resultCode, data); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_demo_get_image, menu); return true; } }
标黄色字体的代码是关键:
Intent intent = new Intent();//新建Intent
//打开Pictures画面Type为image/* intent.setType("image/*"); intent.setAction(intent.ACTION_GET_CONTENT); startActivityForResult(intent, 1);