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>
运行效果:
RecyclerView的使用方法的更多相关文章
- recyclerView中的方法
onCreateViewHolder(); onBindViewHolder(); getItemCount(); recyclerVIew中没有添加头布局和尾布局方法.可以用getItemViewT ...
- 更新RecyclerView的好方法
一般在使用RecyclerView的时候不免要修改RecyclerView的数据,使用notifyDataSetChanged()来刷新界面,但是当数据比较多,而只是修改了一点的数据,或者刷新比较频繁 ...
- ListView的基本使用方法和RecyclerView的基本使用方法
ListView是一种用于列表显示数据内容的控件,它可以通过适配器实现对于数据的列表显示,而RecyclerView是对于ListView优化后的列表数据显示控件. 个人对于List的使用经历多半在新 ...
- RecyclerView使用大全
RecylerView介绍 RecylerView是support-v7包中的新组件,是一个强大的滑动组件,与经典的ListView相比,同样拥有item回收复用的功能,这一点从它的名字recyler ...
- 打造android偷懒神器———RecyclerView的万能适配器
转载请注明出处谢谢:http://www.cnblogs.com/liushilin/p/5720926.html 很不好意思让大家久等了,本来昨天就应该写这个的,无奈公司昨天任务比较紧,所以没能按时 ...
- 自定义RecyclerView.ItemDecoration,实现RecyclerView的分割线效果
[转] 原文 自定义RecyclerView.ItemDecoration,实现RecyclerView的分割线效果 字数1598 阅读302 评论2 喜欢23 1.背景 RecyclerView ...
- RecyclerView 滑动检测 (上滑 up)(下滑 down)(顶部 top)(底部 bottom)
RecyclerView 给我们的可以检测滑动事件的接口 只有 一个方法 recyclerview.setOnScrollListener()或者 recyclerview.addOnScroll ...
- IT蓝豹--RecyclerView加载不同view实现效果
本项目由开发者:黄洞洞精心为初学者编辑RecyclerView的使用方法. RecyclerView加载不同view实现效果,支持加载多个view,并且支持用volley获取数据, 项目主要介绍: 初 ...
- RecyclerView再封装
RecyclerView做为ListView的替代品,已经出了很久了,既然是替代品,那自然有些ListView没有的优点.比如说:可以随意切换list,grid,stagger.可以指定一个或多个it ...
随机推荐
- Struts登录
- 第三章 续:时间控件(TimePicker)
上一章,介绍了datetimepicker使用, 然而,当只需要时分秒的时候,它并不怎么理想,因此又找了一个单独的时间控制插件 现在介绍一个timepicker,用法差不多,但是它只是基于bootst ...
- Android studio导入eclipse项目混淆打包出错
将proguard-android.txt复制一份重命名成proguard-rules.pro,且在build.gradle添加 release { minifyEnabled ...
- Oracle的if else if
前段时间写Oracle存储过程就遇到问题.原来写成这样if 1=2 then null;elseif 1=3 then nullend if;在PL/SQL编辑环境下elseif没有变色,说明不是 ...
- JS案例之8——从一个数组中随机取数
近期项目中遇到一个需求,从一个列表中随机展示列表的部分内容,需求不大,JS也非常容易实现.主要是运用到了Math对象的random方法,和Array的splice方法. 思路是先新建一个数组,存放所有 ...
- 北京联想招聘-Android Framework高级工程师(7-10年) 加入qq 群:220486180 或者直接在此 留言咨询
Job ID #: 45038 Position Title: Android Framework高级工程师 Location: CHN-Beijing Functional Area: Resear ...
- [CareerCup] 2.3 Delete Node in a Linked List 删除链表的节点
2.3 Implement an algorithm to delete a node in the middle of a singly linked list, given only access ...
- swift第一季基础语法
同: 一.基础 同: 1常量和变量 2数据类型和数据类型转换 3别名 不同: 1可选类型optional 2BOOL类型 3元组类型 4断言Assertion 二.基本操作符 同: 1赋值和算术运算及 ...
- 路由器 NorFlash与NandFlash区别
在淘宝上买修改openwrt的路由器,基本上都是改的16MB flash,那么为什么不改到1GB呢? 现在U盘的价格也很便宜啊. 于是我调查了一下,发现flash分为两种,NorFlash与NandF ...
- 谈EntityFramework数据更新之技巧
EntityFramework是一个很不错的ORM框架,一直都在使用.今天想跟大家分享以下EntityFramework数据更新方面的几个技巧: 1:如何new一个新实体去更新记录,而不是从数据库中查 ...