第一步依赖
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.github.bumptech.glide:glide:4.8.0'
RecycleGridActivity
package com.bwei.day13.activity.activity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.bwei.day13.R;
import com.bwei.day13.activity.adapter.GridAdapter;
import com.bwei.day13.activity.bean.User;
import java.net.URL;
public class RecycleGridActivity extends AppCompatActivity {
private RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recycle);
recyclerView = findViewById(R.id.recycler_View);
GridLayoutManager gridLayoutManager = new GridLayoutManager(RecycleGridActivity.this,5);
recyclerView.setLayoutManager(gridLayoutManager);
GridAdapter adapter=new GridAdapter();
for (int i = 0; i <10 ; i++) {
User user = new User();
user.setName("张"+i);
adapter.addItem(user);
}
recyclerView.setAdapter(adapter);
recyclerView.setItemAnimator(new DefaultItemAnimator());
}
}
GridAdapter适配器
package com.bwei.day13.activity.adapter;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bwei.day13.R;
import com.bwei.day13.activity.bean.User;
import java.util.ArrayList;
import java.util.List;
public class GridAdapter extends RecyclerView.Adapter<GridAdapter.VH> {
private final List<User> mData;
public void addItem(User user){
if (user!=null){
mData.add(user);
}
}
public GridAdapter(){
this.mData = new ArrayList<>();
}
@NonNull
@Override
public VH onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
View inflate = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.activity_recycle_grid, viewGroup, false);
return new VH(inflate);
}
@Override
public void onBindViewHolder(@NonNull VH vh, int i) {
User user = mData.get(i);
vh.title.setText(user.getName());
vh.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
@Override
public int getItemCount() {
return mData.size();
}
public static class VH extends RecyclerView.ViewHolder{
private final TextView title;
private final ImageView avatar;
public VH(@NonNull View itemView) {
super(itemView);
title = itemView.findViewById(R.id.title);
avatar = itemView.findViewById(R.id.avatar);
}
}
}