用recylerView實現瀑布流的效果
阿新 • • 發佈:2019-02-05
recylerView是v7包中一個新元件,它具有item回收複用的功能,使用者只要實現自己的ViewHolder就可以了,該元件會自動幫你回收複用每一個item
廢話不多說,直接上程式碼
佈局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <android.support.v7.widget.RecyclerView android:id="@+id/id_recyclerview" android:divider="#ffff0000" android:dividerHeight="10dp" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
程式碼部分:
id_recyclerview = (RecyclerView) findViewById(R.id.id_recyclerview); // 設定佈局管理器 垂直佈局 // id_recyclerview.setLayoutManager(new LinearLayoutManager(this)); //cardView // id_recyclerview.setLayoutManager(new GridLayoutManager(this,5)); //瀑布流 id_recyclerview.setLayoutManager(new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)); id_recyclerview.setItemAnimator(new DefaultItemAnimator()); //建立adapter物件 MyAdapter myAdapter = new MyAdapter(); id_recyclerview.setAdapter(myAdapter); myAdapter.setOnItemClickLitener(new OnItemClickLitener() { @Override public void onItemClick(View view, int position) { Toast.makeText(MainActivity.this,"1111", Toast.LENGTH_LONG).show(); } @Override public void onItemLongClick(View view, int position) { } });
Adaper部分:
@Override public MyViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { MyViewHolder myViewHolder = new MyViewHolder(LayoutInflater.from(MainActivity.this).inflate(R.layout.item_recyclerview,viewGroup,false)); return myViewHolder; } @Override public void onBindViewHolder(MyViewHolder myViewHolder, final int i) { //得到一個隨機數用於設定控制元件高度 Random random = new Random(); int ranHeight = (random.nextInt(10)+5)*15; ViewGroup.LayoutParams linearLayout = ll_randler.getLayoutParams(); linearLayout.height = ranHeight; ll_randler.setLayoutParams(linearLayout); myViewHolder.tv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(onItemClickLitener != null){ onItemClickLitener.onItemClick(v,i); } } }); } @Override public int getItemCount() { return arrayList.size(); } class MyViewHolder extends RecyclerView.ViewHolder{ ImageView tv; //將ViewHolder中的內容寫在裡面,自動複用 public MyViewHolder(View itemView) { super(itemView); tv = (ImageView) itemView.findViewById(R.id.text); ll_randler = (LinearLayout) itemView.findViewById(R.id.ll_randler); } } }