在文件存储部分,利用RecyclerView和SQLite搭建了一个读取本地数据库内容将其显示到列表的demo,这里需要注意的就是数据库的基础操作和RecyclerView的适配器部分,还需要熟练其流程才能掌握。今天的内容是结合之前做的底部导航栏,在切换fragment的时候显示列表,其实实现过程和在Activity里面是类似的。
一、流程
还是梳理一下具体的流程,我的流程如下:
- 在fragment的布局文件中加入RecyclerView的控件;
- 写一个要显示的item布局;
- 写一个POJO类,即一个Item类,设置要显示的变量和构造器,setter and getter;
- 写一个工厂类,用于制造item;
- 主要的是适配器的书写
- 在fragment里面实例化,设置一些RecyclerView的属性
贴上适配器的代码
public class HomeAdapter extends RecyclerView.Adapter <HomeAdapter.MyHolder>{
Context context;
private List<HomeItem> list;
public HomeAdapter(Context context, List<HomeItem> list) {
this.context = context;
this.list = list;
}
@NonNull
@Override
public MyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from (parent.getContext ()).inflate (R.layout.home_list_item_layout,parent,false);
MyHolder holder = new MyHolder (view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull MyHolder holder, int position) {
HomeItem item = list.get (position);
Glide.with (context).load (item.getImgUrl ()).into (holder.ivImage);
holder.tvTitle.setText (item.getImgTitle ());
holder.tvAuthor.setText (item.getImgAuthor ());
holder.tvInfo.setText (item.getImgInfo ());
}
@Override
public int getItemCount() {
return list.size ();
}
class MyHolder extends RecyclerView.ViewHolder {
RelativeLayout itemLayout;
ImageView ivImage;
TextView tvTitle;
TextView tvAuthor;
TextView tvInfo;
public MyHolder(View itemView) {
super (itemView);
itemLayout = itemView.findViewById (R.id.home_list_item_layout_rl);
ivImage = itemView.findViewById (R.id.home_list_item_image_iv);
tvTitle = itemView.findViewById (R.id.home_list_item_title_tv);
tvAuthor = itemView.findViewById (R.id.home_list_item_author_tv);
tvInfo = itemView.findViewById (R.id.home_list_item_info_tv);
}
}
}
二、 注意事项
在fragment实例化的时候注意fragment的生命周期,要在onCreateView()中进行。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
mRecyclerView = view.findViewById (R.id.home_recycler_view_layout);
homeAdapter = new HomeAdapter (getActivity (),list);
mRecyclerView.setLayoutManager (new LinearLayoutManager (getActivity (),LinearLayoutManager.VERTICAL,false));
mRecyclerView.setItemAnimator (new DefaultItemAnimator ());
mRecyclerView.setAdapter (homeAdapter);
mRecyclerView.addItemDecoration (new DividerItemDecoration (getActivity (),DividerItemDecoration.VERTICAL));
return view;
}
三、 Gson的使用
今天还测试了一下Gson的使用,解析json数据。可以结合item的数据用Gson解析后进行显示
网友评论