2024.4.27

一点都不难發表於2024-06-28

Post實體類
package com.example.photo1;

import java.util.List;
import android.net.Uri;

public class Post {
private String text;
private List imageUris;

public Post(String text, List<Uri> imageUris) {
    this.text = text;
    this.imageUris = imageUris;
}

public String getText() {
    return text;
}

public List<Uri> getImageUris() {
    return imageUris;
}

}
post介面卡檔案PostAdapter.java
package com.example.photo1;

import android.content.Context;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import java.util.ArrayList;
import java.util.List;

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> {
private List posts;
private Context context;

public PostAdapter(List<Post> posts, Context context) {
    this.posts = posts;
    this.context = context;
}

@NonNull
@Override
public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(context).inflate(R.layout.post_item, parent, false);
    return new PostViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull PostViewHolder holder, int position) {
    Post post = posts.get(position);
    holder.textViewPost.setText(post.getText());
    Glide.with(context).load(post.getImageUris().get(0)).into(holder.imageViewPost);
}

@Override
public int getItemCount() {
    return posts.size();
}

public static class PostViewHolder extends RecyclerView.ViewHolder {
    TextView textViewPost;
    ImageView imageViewPost;

    public PostViewHolder(@NonNull View itemView) {
        super(itemView);
        textViewPost = itemView.findViewById(R.id.textViewPost);
        imageViewPost = itemView.findViewById(R.id.imageViewPost);
    }
}

}
post_item.xml檔案

<TextView
    android:id="@+id/textViewPost"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="16sp"
    android:textColor="@android:color/black"/>

<ImageView
    android:id="@+id/imageViewPost"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:adjustViewBounds="true"
    android:scaleType="centerCrop"/>