用recylerView实现瀑布流的效果

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);
        }

    }
}



你可能感兴趣的:(框架,android,Activity,RecylerView)