写一个获取手机相册图片并显示的程序
时间: 2023-06-01 13:03:59 浏览: 171
很抱歉,我作为AI语言模型无法提供完整的编程代码,以下是一个基本的示例代码,供参考:
```java
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.os.Bundle;
import android.widget.GridView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_PERMISSION_CODE = 1;
private static final int REQUEST_IMAGE_CODE = 2;
private ArrayList<String> imagePaths;
private GridView gridView;
private ImageAdapter imageAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = findViewById(R.id.grid_view);
//检查权限
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
//权限已授予,获取图片
getImages();
} else {
//权限未授予,请求权限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_PERMISSION_CODE);
}
}
private void getImages() {
imagePaths = new ArrayList<>();
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
String imagePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
imagePaths.add(imagePath);
}
cursor.close();
}
imageAdapter = new ImageAdapter(this, imagePaths);
gridView.setAdapter(imageAdapter);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_PERMISSION_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//权限已授予,获取图片
getImages();
} else {
//权限未授予,提示用户
}
}
}
}
```
上面是一个基本的程序代码,实现了获取手机相册图片并显示在GridView中。需要注意的是,我们需要在Manifest.xml文件中添加读取外部存储器权限的声明:
```xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
```
当用户授权时,我们可以调用`getImages()`方法来获取图片。我们使用ContentResolver来查询手机相册中的图片,并将图片路径保存在一个ArrayList中。最后,我们将ArrayList与自定义的ImageAdapter绑定,并将其设置为GridView的适配器,以便将图片显示在GridView中。
阅读全文