RecyclerView的使用方法
1.添加.jar包
File -> Project-Structure -> 左下角 “app” -> Dependencies -> 右上角“+” -> File dependency -> 选择“com.android.support:recyclerview-v7:23.1.0”
然后在“build-gradle”里面看到“compile ’com.android.support:recyclerview-v7:23.1.0‘”,如果不行,直接复制这句话到这里
MainActivity.java
public class MainActivity extends AppCompatActivity { private RecyclerView mRecyclerView; private List<String> mData; private MyAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initData(); initView(); mAdapter = new MyAdapter(this,mData); mRecyclerView.setAdapter(mAdapter); //AS自带的动画效果 mRecyclerView.setItemAnimator(new DefaultItemAnimator()); //设置RecyclerView的布局管理 LinearLayoutManager manager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false); mRecyclerView.setLayoutManager(manager); //设置RecyclerView的Item间分割线 //直接在item.xml文件中设置android:layout_margin="6dp"取代这句话 mRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL_LIST)); mAdapter.onViewItemClickListener(new MyAdapter.onViewItemClick() { @Override public void onItemClick(View view, int position) { Toast.makeText(MainActivity.this,"Click : "+position,Toast.LENGTH_SHORT).show(); } @Override public void onItemLongClick(View view, int position) { Toast.makeText(MainActivity.this,"Long Click : "+position,Toast.LENGTH_SHORT).show(); mAdapter.itemRemove(position); } }); } private void initData(){ mData = new ArrayList<String>(); for (int i = 'A';i <= 'z';i++) { mData.add(" "+(char)i); } } private void initView() { mRecyclerView = (RecyclerView) findViewById(R.id.rv_recycler); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_add: mAdapter.itemAdd(1); break; case R.id.action_delete: mAdapter.itemRemove(1); break; case R.id.action_diary: mRecyclerView.setLayoutManager(new GridLayoutManager(this,3)); break; case R.id.action_catalog: mRecyclerView.setLayoutManager(new LinearLayoutManager(this)); break; case R.id.action_more: mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(4,StaggeredGridLayoutManager.VERTICAL)); break; case R.id.action_demo: Intent intent = new Intent(MainActivity.this,StraggedGridViewActivity.class); startActivity(intent); } return super.onOptionsItemSelected(item); } }
MyAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> { private List<String> mData; private LayoutInflater mInflater; private Context mContext; private onViewItemClick onViewItemClickListener; public void onViewItemClickListener(onViewItemClick listener){ this.onViewItemClickListener = listener; } public MyAdapter(Context context,List<String> data) { this.mContext = context; this.mData = data; this.mInflater = LayoutInflater.from(context); } //创建ViewHolder @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = mInflater.inflate(R.layout.item,parent,false); MyViewHolder viewHolder = new MyViewHolder(view); return viewHolder; } //绑定ViewHolder //final是自动添加上去的 @Override public void onBindViewHolder(final MyViewHolder holder, final int position) { holder.tv.setText(mData.get(position)); /*if (onViewItemClickListener != null) { holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onViewItemClickListener.onItemClick(holder.itemView,position); } }); }*/ holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //直接position不会刷新位置信息 int layoutPosition = holder.getLayoutPosition(); //onViewItemClickListener.onItemClick(holder.itemView,position); onViewItemClickListener.onItemClick(holder.itemView,layoutPosition); } }); holder.itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { int layoutPosition = holder.getLayoutPosition(); onViewItemClickListener.onItemLongClick(holder.itemView,layoutPosition); return false; } }); } @Override public int getItemCount() { //return 0; return mData.size(); } //自定义添加item方法 public void itemAdd(int position) { //不是notifyItemChanged(),这是把position位置的给取代了 mData.add(position, "SSS"); notifyItemInserted(position); //notifyItemChanged(position); } //自定义删除item方法 public void itemRemove(int position) { mData.remove(position); notifyItemRemoved(position); } //监听点击事件的接口 public interface onViewItemClick { void onItemClick(View view, int position); void onItemLongClick(View view, int position); } } //MyViewHolder拥有所有item.xml的控件 class MyViewHolder extends RecyclerView.ViewHolder { //tv不能是private,因为MyAdapter类中的onBindViewHolder()要调用 TextView tv; public MyViewHolder(View itemView) { super(itemView); tv = (TextView) itemView.findViewById(R.id.tv_text); } }
StraggedGridViewActivity.java
public class StraggedGridViewActivity extends AppCompatActivity { private RecyclerView mRecyclerView; private List<String> mData; private StraggedGridViewAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_stragged_grid_view); initData(); initView(); mAdapter = new StraggedGridViewAdapter(this,mData); mRecyclerView.setAdapter(mAdapter); mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(3,StaggeredGridLayoutManager.VERTICAL)); } private void initData(){ mData = new ArrayList<String>(); for (int i = 'A';i <= 'z';i++) { mData.add(" "+(char)i); } } private void initView() { mRecyclerView = (RecyclerView) findViewById(R.id.rv_recycler); } }
StraggedGridViewAdapter.java
public class StraggedGridViewAdapter extends RecyclerView.Adapter<MyViewHolder2> { private List<String> mData; private LayoutInflater mInflater; private Context mContext; private List<Integer> mHeight; public StraggedGridViewAdapter(Context context,List<String> data) { this.mContext = context; this.mData = data; this.mInflater = LayoutInflater.from(context); mHeight = new ArrayList<Integer>(); for (int i = 0;i <mData.size();i++) { mHeight.add((int) (100+Math.random()*300)); } } //创建ViewHolder @Override public MyViewHolder2 onCreateViewHolder(ViewGroup parent, int viewType) { View view = mInflater.inflate(R.layout.item,parent,false); MyViewHolder2 viewHolder = new MyViewHolder2(view); return viewHolder; } //绑定ViewHolder @Override public void onBindViewHolder(MyViewHolder2 holder, int position) { //动态高度的设置 ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams(); lp.height = mHeight.get(position); holder.itemView.setLayoutParams(lp); holder.tv.setText(mData.get(position)); } @Override public int getItemCount() { //return 0; return mData.size(); } } //MyViewHolder拥有所有item.xml的控件 class MyViewHolder2 extends RecyclerView.ViewHolder { //tv不能是private,因为MyAdapter类中的onBindViewHolder()要调用 TextView tv; public MyViewHolder2(View itemView) { super(itemView); tv = (TextView) itemView.findViewById(R.id.tv_text); } }
DividerItemDecoration.java //这是分割线,可以不要,在divider.xml和styles.xml里面可以取代
public class DividerItemDecoration extends RecyclerView.ItemDecoration { private static final int[] ATTRS = new int[] { android.R.attr.listDivider }; public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL; public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL; private Drawable mDivider; //item间间隔图片资源 private int mOrientation; //方向:水平,垂直 public DividerItemDecoration(Context context, int orientation) { final TypedArray a = context.obtainStyledAttributes(ATTRS); mDivider = a.getDrawable(0); a.recycle(); setOrientation(orientation); } public void setOrientation(int orientation) { if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) { throw new IllegalArgumentException("invalid orientation"); } mOrientation = orientation; } @Override public void onDraw(Canvas c, RecyclerView parent) { //Log.v("recyclerview - itemdecoration", "onDraw()"); if (mOrientation == VERTICAL_LIST) { drawVertical(c, parent); } else { drawHorizontal(c, parent); } } public void drawVertical(Canvas c, RecyclerView parent) { final int left = parent.getPaddingLeft(); final int right = parent.getWidth() - parent.getPaddingRight(); final int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); RecyclerView v = new RecyclerView( parent.getContext()); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child .getLayoutParams(); final int top = child.getBottom() + params.bottomMargin; final int bottom = top + mDivider.getIntrinsicHeight(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } public void drawHorizontal(Canvas c, RecyclerView parent) { final int top = parent.getPaddingTop(); final int bottom = parent.getHeight() - parent.getPaddingBottom(); final int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child .getLayoutParams(); final int left = child.getRight() + params.rightMargin; final int right = left + mDivider.getIntrinsicHeight(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } //提供绘制分割线的间隙 @Override public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) { if (mOrientation == VERTICAL_LIST) { outRect.set(0, 0, 0, mDivider.getIntrinsicHeight()); } else { outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0); } } }
main_activity.xml
<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" tools:context=".MainActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/rv_recycler" android:layout_height="match_parent" android:layout_width="match_parent"/> </RelativeLayout>
activity_stragged_grid_view.xml
<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:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="my.com.example.x550v.recyclerviewdemo.StraggedGridViewActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/rv_recycler" android:layout_height="match_parent" android:layout_width="match_parent"/> </RelativeLayout>
item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/button" android:layout_marginTop="8dp" android:layout_marginBottom="8dp" android:layout_marginRight="5dp" android:layout_marginLeft="5dp" android:orientation="vertical"> <TextView android:id="@+id/tv_text" android:gravity="center" android:textColor="#fff" android:textSize="20sp" android:layout_gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
divider.xml
<!--写完后要在styles里面声明--> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <size android:height="4dp"/> <gradient android:startColor="#000" android:centerColor="#fff" android:endColor="#fff" android:type="linear"/> </shape>
buttom.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="false"> <shape android:shape="rectangle"> <gradient android:angle="45" android:centerX="35%" android:centerColor="#43D2E8" android:startColor="#43D2E8" android:endColor="#000000" android:type="linear" /> </shape> </item> <item android:state_pressed="true" > <shape android:shape="rectangle"> <gradient android:angle="45" android:centerX="35%" android:centerColor="#B3DDE8" android:startColor="#43D2E8" android:endColor="#000000" android:type="linear" /> </shape> </item> </selector>
menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context="my.com.example.x550v.recyclerviewdemo.MainActivity"> <item android:id="@+id/action_add" android:title="Add" android:icon="@android:drawable/ic_media_play" app:showAsAction="ifRoom"/> <item android:id="@+id/action_delete" android:title="Add" android:icon="@android:drawable/ic_media_pause" app:showAsAction="ifRoom"/> <item android:id="@+id/action_both" android:title="action" android:icon="@android:drawable/ic_input_add" app:showAsAction="ifRoom|collapseActionView"> <menu> <item android:id="@+id/action_diary" android:title="GirdView" android:icon="@android:drawable/ic_menu_save" app:showAsAction="ifRoom"/> <item android:id="@+id/action_catalog" android:title="LinearView" android:icon="@android:drawable/ic_menu_sort_by_size" app:showAsAction="ifRoom"/> <item android:id="@+id/action_more" android:title="StaggeredGridView" android:icon="@android:drawable/ic_menu_myplaces" app:showAsAction="ifRoom"/> <item android:id="@+id/action_demo" android:title="StaggeredGridDemoView" android:icon="@android:drawable/ic_menu_mapmode" app:showAsAction="ifRoom"/> </menu> </item> </menu>
styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> <!--设置分割线--> <item name="android:listDivider">@drawable/diver</item> </style>
运行效果: