从媒体库中选择图片
主要是启动系统相关Activity
Intent i = new Intent( Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
startActivityForResult(i, RESULT_LOAD_IMAGE);
注意:这里要传一个整形的常量RESULT_LOAD_IMAGE到startActivityForResult()
方法。
一旦用户选择了一张图片,onActivityResult()方法将会被调用。我们需要处理这个方法得到的数据。onActivityResult()方法只有当图片被选中后才会调用。在这个方法中,我们需要检查requestCode是否是我们之前传给startActivityForResult()方法的RESULT_LOAD_IMAGE。
Java代码:
package com.example.com.njupt.zhb.selectimages;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
private static int RESULT_LOAD_IMAGE = 123;
private ImageView imageView;
private String picturePath=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imgView);
Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
XML布局文件
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
android:id="@+id/widget0"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="@+id/imgView"
android:layout_width="315dp"
android:layout_height="384dp"
android:layout_x="2dp"
android:layout_y="4dp" />
<Button
android:id="@+id/buttonLoadPicture"
android:layout_width="317dp"
android:layout_height="wrap_content"
android:text="SelectImage"
android:layout_x="2dp"
android:layout_y="391dp" />
</AbsoluteLayout>