主布局XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/mybtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Press Me" />
<ImageView
android:id="@+id/myimage"
android:layout_width="200dip"
android:layout_height="200dip"
android:layout_below="@id/mybtn"
android:layout_centerHorizontal="true"
android:scaleType="centerInside" />
</RelativeLayout>
源码:
public class MainActivity extends Activity {
private Button myBtn = null;
private ImageView myImageView = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myImageView = (ImageView)findViewById(R.id.myimage);
myBtn = (Button)findViewById(R.id.mybtn);
myBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
// 打开Pictures画面Type为image/*
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 1);
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (RESULT_OK == resultCode) {
Uri uri = data.getData();
ContentResolver cr = this.getContentResolver();
try {
Bitmap bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
myImageView.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
效果图: