Android之RecycleView使用(瀑布流管理器及線性流管理器)
阿新 • • 發佈:2019-02-03
public class RecyclerActivity extends Activity { @Bind(R.id.rv) RecyclerView rv; private List<Map> list; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_recycler); ButterKnife.bind(this); list =new ArrayList<>(); initDate(); MyAdapter myAdapter =new MyAdapter(list); //瀑布流管理器 StaggeredGridLayoutManager sgm = new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL); rv.setLayoutManager(sgm); rv.setAdapter(myAdapter); //設定分割線 DividerItemDecoration itemDecoration = new DividerItemDecoration(this,DividerItemDecoration.VERTICAL_LIST); rv.addItemDecoration(itemDecoration); } public void initDate(){ HashMap map =new HashMap(); map.put("img",R.mipmap.a); map.put("text","x1"); list.add(map); map=new HashMap(); map.put("img",R.mipmap.b); map.put("text","x2"); list.add(map); map=new HashMap(); map.put("img",R.mipmap.as); map.put("text","x3"); list.add(map); map=new HashMap(); map.put("img",R.mipmap.e); map.put("text","x2"); list.add(map); map=new HashMap(); map.put("img",R.mipmap.e); map.put("text","x3"); list.add(map); map=new HashMap(); map.put("img",R.mipmap.as); map.put("text","x2"); list.add(map); map=new HashMap(); map.put("img",R.mipmap.lh3); map.put("text","x3"); list.add(map); map=new HashMap(); map.put("img",R.mipmap.b); map.put("text","x2"); list.add(map); map=new HashMap(); map.put("img",R.mipmap.as); map.put("text","x3"); list.add(map); map=new HashMap(); map.put("img",R.mipmap.lh1); map.put("text","x2"); list.add(map); map=new HashMap(); map.put("img",R.mipmap.lh2); map.put("text","x3"); list.add(map); } public class MyAdapter extends RecyclerView.Adapter<MyViewHolder>{ private List<Map> mapList; public MyAdapter(List<Map> mapList) { this.mapList = mapList; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view=LayoutInflater.from(getBaseContext()).inflate(R.layout.recycle_stag,parent,false); MyViewHolder viewHolder = new MyViewHolder(view); return viewHolder; } //繫結 @Override public void onBindViewHolder(MyViewHolder holder, int position) { Map map = mapList.get(position); holder.imageView.setImageResource((Integer) map.get("img")); holder.textView.setText(map.get("text").toString()); } @Override public int getItemCount() { return mapList.size(); } } public class MyViewHolder extends RecyclerView.ViewHolder{ ImageView imageView; TextView textView; public MyViewHolder(View itemView) { super(itemView); imageView=(ImageView)itemView.findViewById(R.id.iv); textView =(TextView)itemView.findViewById(R.id.tvi1); } } }