1的详细代码
时间: 2024-02-16 15:59:52 浏览: 144
好的,下面是实现简易相册的详细代码:
1. 在XML文件中添加GridView组件,例如:
```xml
<GridView
android:id="@+id/grid_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"
android:verticalSpacing="5dp"
android:horizontalSpacing="5dp"
android:stretchMode="columnWidth" />
```
2. 创建一个Photo类,例如:
```java
public class Photo {
private String path;
private String name;
public Photo(String path, String name) {
this.path = path;
this.name = name;
}
public String getPath() {
return path;
}
public String getName() {
return name;
}
}
```
3. 创建一个PhotoAdapter类,例如:
```java
public class PhotoAdapter extends BaseAdapter {
private Context context;
private List<Photo> photoList;
public PhotoAdapter(Context context, List<Photo> photoList) {
this.context = context;
this.photoList = photoList;
}
@Override
public int getCount() {
return photoList.size();
}
@Override
public Object getItem(int position) {
return photoList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.grid_item_photo, parent, false);
}
ImageView imageView = convertView.findViewById(R.id.image_view);
String path = photoList.get(position).getPath();
Glide.with(context).load(path).into(imageView);
return convertView;
}
}
```
4. 在Activity中读取相册中的图片,例如:
```java
private void loadPhotos() {
String[] projection = {MediaStore.Images.Media.DATA, MediaStore.Images.Media.DISPLAY_NAME};
Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
if (cursor != null) {
List<Photo> photoList = new ArrayList<>();
while (cursor.moveToNext()) {
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
String name = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME));
photoList.add(new Photo(path, name));
}
cursor.close();
PhotoAdapter photoAdapter = new PhotoAdapter(this, photoList);
gridView.setAdapter(photoAdapter);
}
}
```
5. 在GridView中显示图片,例如:
```xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop" />
```
6. 当用户点击某张图片时,可以使用Intent打开该图片并进行查看,例如:
```java
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String path = photoList.get(position).getPath();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + path), "image/*");
startActivity(intent);
}
});
```
以上就是实现简易相册的详细代码,希望能对你有所帮助。
阅读全文