package com.example.administrator.recyclerview; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.View; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { RecyclerView mRecyclerView; MyAdapter adapter; Dates dates; List<Dates> mDate; int[] imageId={R.mipmap.love_card_avar,R.mipmap.love_card_img1, R.mipmap.love_card_img2,R.mipmap.love_card_img3,R.mipmap.love_card_img4 ,R.mipmap.love_card_img5 }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 初始化对象,实现绑定 mRecyclerView= (RecyclerView) findViewById(R.id.recyclerView); initDates(); // 创建数据源 adapter=new MyAdapter(MainActivity.this,mDate); // 使用adapter来设置点击事件,由于点击事件是在MyAdapter中定义的所以要由MyAdapter的对象来调用 adapter.setOnRecyclerViewItemClickListener(new MyAdapter.OnRecyclerViewItemClickListener() { @Override public void OnItem(View view, int position) { Toast.makeText(MainActivity.this, "item点击事件", Toast.LENGTH_SHORT).show(); } }); // 设置适配器 mRecyclerView.setAdapter(adapter); // 设置横向滑动的item 用LinearLayoutManager.HORIZONTAL // GridLayoutManager(this,2, LinearLayoutManager.HORIZONTAL,false)中 // GridLayoutManager layoutManager=new GridLayoutManager(this,2, LinearLayoutManager.HORIZONTAL,false); // 设置垂直滑动的item用LinearLayoutManager.VERTICAL,参数列表含义:本类即上下文,排列行数或者列数,排列类型,false // GridLayoutManager layoutManager=new GridLayoutManager(this,3,LinearLayoutManager.VERTICAL,false); // LinearLayoutManager效果如同ListView的展示效果单行或者单列,参数列表含义:上下文即本类,排列类型,false // LinearLayoutManager layoutManager=new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false); // StaggeredGridLayoutManager为瀑布流的布局管理工具,参数列表的含义:列数或者行数,排列类型 StaggeredGridLayoutManager layoutManager=new StaggeredGridLayoutManager(2,LinearLayoutManager.VERTICAL); // RecycleView中onCreateViewHolder并没有将item填充到页面中,还需要调用 setLayoutManager();方法是将item填充到页面 mRecyclerView.setLayoutManager(layoutManager); // 设置增删除item的动画 mRecyclerView.setItemAnimator(new DefaultItemAnimator()); // 设置线型 mRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.HORIZONTAL_LIST)); mRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL_LIST)); } // 设置数据源,用for循环的方法创建集合的数据源 public void initDates(){ mDate=new ArrayList<>(); for (int i=0;i<6;i++){ dates=new Dates(imageId[i]); mDate.add(dates); } } }