Activity
public class ShowActivity extends AppCompatActivity {
Context context;
@BindView(R.id.rv_container)
RecyclerView rvContainer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
//上下文
context = ShowActivity.this;
//网络请求
OkGo.<String>get(Constant.BEAUTY_URL).execute(new StringCallback() {
@Override
public void onSuccess(Response<String> response) {
String responseData = response.body().toString();
Toast.makeText(context, responseData, Toast.LENGTH_SHORT).show();
Log.e("ShowActivity", responseData);
//数据解析
Gson gson = new Gson();
BeautyBean beautyBean = gson.fromJson(responseData, BeautyBean.class);
//1、数据源
ArrayList<BeautyBean.ResultsBean> beanList = (ArrayList<BeautyBean.ResultsBean>) beautyBean.getResults();
//2、*布局管理器
//①线性 LinearLayoutManager
//②网格 GridLayoutManager
//③瀑布流 StaggeredGridLayoutManager
//LinearLayoutManager manager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
//GridLayoutManager manager = new GridLayoutManager(context, 2,GridLayoutManager.VERTICAL,false);
StaggeredGridLayoutManager manager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
rvContainer.setLayoutManager(manager);
//3、*适配器
BeautyAdapter beautyAdapter = new BeautyAdapter();
beautyAdapter.setData(context, beanList);
//设置适配器
rvContainer.setAdapter(beautyAdapter);
beautyAdapter.notifyDataSetChanged();
}
});
}
}
Adapter
public class BeautyAdapter extends RecyclerView.Adapter<BeautyAdapter.SubViewHolder> {
ArrayList<BeautyBean.ResultsBean> beanList;
Context context;
//接收数据
public void setData(Context context, ArrayList<BeautyBean.ResultsBean> beanList) {
this.beanList = beanList;
this.context = context;
}
@NonNull
@Override
public SubViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int position) {
//填充子布局
View rootView = LayoutInflater.from(context).inflate(R.layout.recyclerview_item_layout, viewGroup, false);
//设置ViewHolder
SubViewHolder subViewHolder = new SubViewHolder(rootView);
return subViewHolder;
}
@Override
public void onBindViewHolder(@NonNull SubViewHolder subViewHolder, int position) {
subViewHolder.tvTitle.setText("创建时间是:" + beanList.get(position).getCreatedAt());
//Glide加载图片
Glide.with(context).load(beanList.get(position).getUrl()).into(subViewHolder.ivIcon);
}
@Override
public int getItemCount() {
//条目数
return beanList.size();
}
class SubViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.tv_title)
TextView tvTitle;
@BindView(R.id.iv_icon)
ImageView ivIcon;
public SubViewHolder(@NonNull View itemView) {
super(itemView);
//ButterKnife绑定
//注意,在这里,Bind需要传入绑定的类对象,传入绑定的视图对象
ButterKnife.bind(this, itemView);
}
}
}