调用系统的相册(展示图片)

添加权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<Button
android:id="@+id/but"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:text="点击选择图片" />

<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>






public class MainActivity extends AppCompatActivity implements View.OnClickListener {
//调用系统相册-选择图片
private static final int IMAGE = 1;
/**
* 点击选择图片
*/
private Button mBut;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}

public void onClick(View v) {
//调用相册
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, IMAGE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//获取图片路径
if (requestCode == IMAGE && resultCode == Activity.RESULT_OK && data != null) {
Uri selectedImage = data.getData();
String[] filePathColumns = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePathColumns[0]);
String imagePath = c.getString(columnIndex);
showImage(imagePath);
c.close();
}
}

//加载图片
private void showImage(String imaePath) {
Bitmap bm = BitmapFactory.decodeFile(imaePath);
((ImageView) findViewById(R.id.image)).setImageBitmap(bm);
}

private void initView() {
mBut = (Button) findViewById(R.id.but);
mBut.setOnClickListener(this);
}
}
原文地址:https://www.cnblogs.com/ysxy/p/9003129.html