1. 程式人生 > >RecycleView實現瀑布流的效果

RecycleView實現瀑布流的效果

public class MainActivity extends AppCompatActivity {
    private RecyclerView recycleview;
    private int image[] = {R.drawable.pre12,  R.drawable.pre15,R.drawable.pre19,
            R.drawable.pre13,R.drawable.pre14, R.drawable.pre15, R.drawable.pre21,
            R.drawable.pre16, R.drawable.pre17, R.drawable.pre19,
            R.drawable.pre21,  R.drawable.pre15, R.drawable.pre22};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recycleview = (RecyclerView) findViewById(R.id.Recycle_View);
    }

    private void StaggerLoadData(Boolean inversion,Boolean orientation) {
        //集合物件
        ArrayList<DataBean> list = new ArrayList<>();
        //給DataBean類放資料,最後把裝好資料的DataBean類放到集合裡
        for(int i=0;i<image.length;i++){
            //建立DataBean類物件,
            DataBean dataBean=new DataBean();
            dataBean.Icon = image[i];
            dataBean.name ="美女"+i;
            //把DataBean類放入集合裡
            list.add(dataBean);
        }
        //建立介面卡Adapter物件  引數:1.上下文2.資料載入集合
        MyRecycleStaggerAdapter adapter = new MyRecycleStaggerAdapter(this,list);
        //設定介面卡
        recycleview.setAdapter(adapter);
        //new Stagger佈局管理器,佈局管理器所需引數:1.規定顯示幾列 2.item排列方向
        StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(2, orientation ? StaggeredGridLayoutManager.VERTICAL : StaggeredGridLayoutManager.HORIZONTAL);
        //通過佈局管理器控制條目排列的順序  true:反向顯示 false:正向顯示
        staggeredGridLayoutManager.setReverseLayout(inversion);
        //設定佈局管理器,引數StaggeredGridLayoutManager,可以是RecyclerView實現和StaggeredGridView一樣的效果
        recycleview.setLayoutManager(staggeredGridLayoutManager);
    }
    //選單,RecycleView各種效果的展示
    //載入一個選單的佈局
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //載入佈局使用選單特有方法getMenuInflater。或Inflate物件,引數:1.選單顯示的不就 2.固定menu
        getMenuInflater().inflate(R.menu.menu_item, menu);
        return true;
    }

    @Override
    //選單按鈕點選事件的處理
    public boolean onOptionsItemSelected(MenuItem item) {
        //獲取item的id
        int itemId = item.getItemId();
        //stagger標準顯示
        if (itemId == R.id.action_stagger_normal) {
            StaggerLoadData(false, true);
            return true;
        }//stagger垂直顯示
        else if (itemId == R.id.action_stagger_reverse) {
            StaggerLoadData(true, true);
        }//stagger水平顯示
        else if (itemId == R.id.action_stagger_horizontal) {
            StaggerLoadData(false, false);
        }//stagger水平反向顯示
        else if (itemId == R.id.action_stagger_horizontal_reverse) {
            StaggerLoadData(true, false);
        }
        return super.onOptionsItemSelected(item);
    }
}