xml布局activity_main:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/picture"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="选择图片" />
<ImageView
android:id="@+id/src"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
</LinearLayout>
MainActivity.java:
public class MainActivity extends Activity {
private final int REQUEST_PICTURE_CHOOSE=1;
Button btn;
ImageView img;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
init();
event();
}
private void init() {
// TODO Auto-generated method stub
btn = (Button) findViewById(R.id.picture);
img = (ImageView) findViewById(R.id.src);
}
private void event() {
// TODO Auto-generated method stub
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(intent, REQUEST_PICTURE_CHOOSE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
String fileSrc = null;
if (requestCode == Constants.REQUEST_PICTURE_CHOOSE) {
if ("file".equals(data.getData().getScheme())) {
// 有些低版本机型返回的Uri模式为file
fileSrc = data.getData().getPath();
} else {
// Uri模型为content
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(data.getData(),
proj, null, null, null);
cursor.moveToFirst();
int idx = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
fileSrc = cursor.getString(idx);
cursor.close();
}
//以下bitmap最好先进行缩放处理,这里就不处理了
Bitmap bitmap= BitmapFactory.decodeFile(fileSrc);
img.setImageBitmap(bitmap);
}
}
}
添加权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />