java 如何将Cardview与RecyclerView + Retrofit一起使用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 如何将Cardview与RecyclerView + Retrofit一起使用相关的知识,希望对你有一定的参考价值。

// Adding libraries first

implementation 'com.android.support:cardview-v7:27.1.1'
implementation 'com.android.support:recyclerview-v7:27.1.1'

// Retrofit libraries

implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 	'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
// Add Internet Permision to file

<uses-permission android:name="android.permission.INTERNET"/>
//Cardview Example. Should contain the structure of the data

<android.support.v7.widget.CardView 
    android:id="@+id/cv"
    android:layout_width="168dp"
    android:layout_height="230dp"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_margin="2dp"
    app:cardCornerRadius="8dp"
    app:cardElevation="4dp"
    xmlns:android="http://schemas.android.com/apk/res/android" >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/user_id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />

        <TextView
            android:id="@+id/id"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/body"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
    </LinearLayout>
</android.support.v7.widget.CardView>
// Should be added in the activity where our Recyclerview is going to be placed.

<android.support.v7.widget.RecyclerView
    android:id="@+id/rv"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />
// Java Model Example.

public class Post {

    @SerializedName("userId")
    private Integer userId;
    @SerializedName("id")
    private Integer id;
    @SerializedName("title")
    private String title;
    @SerializedName("body")
    private String body;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    @Override
    public String toString() {
        return "Post{" +
                "userId=" + userId +
                ", id=" + id +
                ", title='" + title + '\'' +
                ", body='" + body + '\'' +
                '}';
    }
}
// View.OnClickListener only necesary when each cardview can be clicked

public class RecyclerViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    TextView user_id;
    TextView post_id;
    TextView post_title;
    TextView post_body;
    CardView cv;


    public RecyclerViewHolder(View itemView) {
        super(itemView);
        itemView.setOnClickListener(this);
        cv = itemView.findViewById(R.id.cv);
        user_id = itemView.findViewById(R.id.user_id);
        post_id = itemView.findViewById(R.id.id);
        post_title = itemView.findViewById(R.id.title);
        post_body = itemView.findViewById(R.id.body);
    }

    @Override
    public void onClick(View v) {

    }
}
// Adapter that connects RecyclerViewHolder with the Inflated Cardview

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
    
    private List<Post> postList;
    private Context context;

    public RecyclerViewAdapter(List<Post> postList, Context context) {
        this.postList = postList;
        this.context = context;
    }
    
    public void setPostList(List<Post> postList) {
        this.postList = postList;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View lv = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_posts,parent,false);
        RecyclerViewHolder recyclerViewHolder = new RecyclerViewHolder(lv);
        return recyclerViewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) {
        // Remember to check is data is a String or a number
        
        holder.user_id.setText(String.valueOf(postList.get(position).getUserId()));
        holder.post_id.setText(String.valueOf(postList.get(position).getId()));
        holder.post_title.setText(postList.get(position).getTitle());
        holder.post_body.setText("Aqui va el body");
        
    }

    @Override
    public int getItemCount() {
        if(postList != null){
            return this.postList.size();
        }
        return 0;
    }

    @Override
    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }
}
// ApiInterface and Calls used for Retrofit

public class MainActivity extends AppCompatActivity {

    List<Post> postList;
    RecyclerView recyclerView;
    RecyclerViewAdapter recyclerViewAdapter;

    RecyclerView.LayoutManager layoutManager;

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

        recyclerView = findViewById(R.id.recyclerView);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);

        recyclerViewAdapter = new RecyclerViewAdapter(postList,getApplicationContext());
        recyclerView.setAdapter(recyclerViewAdapter);



        postList = new ArrayList<>();
        ApiInterface apiInterface = ApiClient.getClient().create(ApiInterface.class);

        Call<List<Post>> call = apiInterface.getPosts();

        call.enqueue(new Callback<List<Post>>() {
            @Override
            public void onResponse(Call<List<Post>> call, Response<List<Post>> response) {


                postList = response.body();
                Log.d("MainActivity",postList.toString());
                recyclerViewAdapter.setPostList(postList);

            }

            @Override
            public void onFailure(Call<List<Post>> call, Throwable t) {
                Log.d("MainActivity",t.toString());

            }
        });

    }
public class ApiClient {

    private static final String BASE_URL = "https://jsonplaceholder.typicode.com/posts/";
    private static Retrofit retrofit;

    public static Retrofit getClient(){
        if(retrofit == null){
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}
public interface ApiInterface {

    @GET("/posts")
    Call<List<Post>> getPosts();
}

以上是关于java 如何将Cardview与RecyclerView + Retrofit一起使用的主要内容,如果未能解决你的问题,请参考以下文章

从 RecyclerView 单击 CardView 加载片段

如何在 JSON 的 Recycler 视图中显示特定类别

使用 android studio java Recycler 视图从 Firebase 实时数据库中删除一个节点

如何从android studio中的recycler视图将数据添加到SQLite数据库中

Android CardView 实现

如何将Firebase Recycler视图从最新(列表顶部)排序到最旧[重复]