前言
在相册里选择图片上传也是很常见的功能了例如微信朋友圈等等。但是他们是自定义的选择器,可以选择多张图片并修改。这里我们讲一个最简单的:调用系统的相册选择一张图片并展示。另外有的读者还想到要通过相机拍照来选择图片的功能,也可以参考一下我的另一篇文章学习笔记之Android使用系统相机进行拍照
使用步骤
这里我是通过一个简单的demo来讲解怎么去实现这个功能。首先看布局:
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginEnd="52dp"
android:layout_marginRight="52dp"
android:text="choose"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="29dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button"
app:srcCompat="@mipmap/ic_launcher_round" />
很简单,就是一个按钮和一个imageView。然后接下来让我们想想这个功能怎么去实现:
首先打开相册,那么肯定要通过隐式启动相册activity;然后相册返回一个路径,我们就拿这个路径把路径上对应的照片展示出来。思路挺简单的,让我们写写看:
首先看代码:
private Uri imageUri;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
Button button1 = findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick