生活本來(lái)就不容易,而我們的不努力只會(huì)讓生活變得更加無(wú)賴
前幾天依據(jù)《Android群英傳》的學(xué)習(xí)寫了一篇筆記是關(guān)于ListView的基本使用
但是Google已經(jīng)推出了更加自由的RecyclerView取代ListView,所以這兩天特地花時(shí)間學(xué)習(xí)了一下RecyclerView的基本用法,今天寫的這篇將實(shí)現(xiàn)RecyclerView的基本功能如基本使用,添加分界線,拖拽移動(dòng),滑動(dòng)刪除等,過幾天再接著學(xué)習(xí)更高級(jí)的功能,
整體預(yù)覽:
基本用法
我們知道RecyclerView是用以取代ListView和GridView的,所以依據(jù)后兩者用法可知,RecyclerView必須要有一樣?xùn)|西,適配器Adapter, 而Adapter則需要數(shù)據(jù)項(xiàng)以及view填充
- item_viewholder.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#44ff00">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hello"
android:textColor="#fff"
android:textSize="40sp"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:id="@+id/text_view"/>
</LinearLayout>```
* activity_main.xml
<LinearLayout 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" tools:context="com.lqg.myrecyclerview.MainActivity">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:id="@+id/tool_bar"
app:title="RecyclerDemo"
app:titleTextColor="@android:color/white"
android:background="@color/colorPrimary">
</android.support.v7.widget.Toolbar>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/recycler_view">
</android.support.v7.widget.RecyclerView>
</LinearLayout>```
- 基本實(shí)現(xiàn)
MyAdapter.java
public class MyAadapter extends RecyclerView.Adapter{
private LayoutInflater inflater;
public List<String> list;
public MyAadapter(Context context , List<String> list) {
this.list = list;
inflater = LayoutInflater.from(context);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(inflater.inflate(R.layout.item_viewholder,parent,false));
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final ViewHolder viewHolder = (ViewHolder) holder;
viewHolder.textview.setText(list.get(position));
}
@Override
public int getItemCount() {
return list.size();
}
private class ViewHolder extends RecyclerView.ViewHolder{
private TextView textview;
public ViewHolder(View itemView) {
super(itemView);
textview = (TextView) itemView.findViewById(R.id.text_view);
}
}
}```
MainActivity.java
public class MainActivity extends AppCompatActivity implements Toolbar.OnMenuItemClickListener {
private RecyclerView recyclerView;
private List<String> mDatas;
private MyAadapter myAadapter;
private MyAadapter.OnClickListener mOnClickListener;
private Toolbar mToolbar;
private RecyclerView.LayoutManager manager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatas = getList();
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setLayoutManager(new LinearLayoutManager(this));
myAadapter = new MyAadapter(this,mDatas);
recyclerView.setAdapter(myAadapter);
//Toolbar
mToolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(mToolbar);
mToolbar.setOnMenuItemClickListener(this);
}
//獲取List方法
private List<String> getList(){
List<String> list = new ArrayList<String>();
for (int i = 'A';i<'z';++i){
list.add(""+(char)i);
}
return list;
}
其中需要注意的一點(diǎn)就是```setLayoutManager```這個(gè)方法是設(shè)置一個(gè)LayoutManager的.其中選項(xiàng)為L(zhǎng)inearLayoutManager()線性),GridLayoutManager(網(wǎng)格)以及StaggerGridLayoutManager(瀑布流)三種
效果
![linearLayout.gif](http://upload-images.jianshu.io/upload_images/2605454-4c18264dd6588683.gif?imageMogr2/auto-orient/strip)
![grid.gif](http://upload-images.jianshu.io/upload_images/2605454-8ba54cceab1f52c5.gif?imageMogr2/auto-orient/strip)
![stagger.gif](http://upload-images.jianshu.io/upload_images/2605454-125c6e07fc3f4c0f.gif?imageMogr2/auto-orient/strip)
就問你一句,丑不丑!不過沒關(guān)系,丑是因?yàn)樗凶冹诺馁Y本,下面添加分割線
#### 分割線
想要理解分割線的概念,首先得新建類實(shí)現(xiàn)```RecyclerView.ItemDecoration```;接著理解幾個(gè)簡(jiǎn)單的概念,不過一幅圖就能解決的事盡量憋說(shuō)話
![Paste_Image.png](http://upload-images.jianshu.io/upload_images/2605454-74568052f8c85b24.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
下面從代碼張進(jìn)一步理解
* LinearLayout的分割線類:DividerItemDecolation.java
public class DividerItemDecpration extends RecyclerView.ItemDecoration{
/**
* 巧妙利用系統(tǒng)自帶,可定制
*/
private final static int[] ATTRS = {android.R.attr.listDivider};
/**
* 獲取布局走向
*/
private final static int ORIENTETION_VERTIVAL = LinearLayoutManager.VERTICAL;
private final static int ORIENTATION_HORIZONTAL =LinearLayoutManager.HORIZONTAL;
private Drawable mDivider;
private int mOrientation;
/**
* 構(gòu)造方法,獲取系統(tǒng)屬性,猴設(shè)置布局走向
*/
public DividerItemDecpration(Context context ,int Orientation) {
TypedArray ta = context.obtainStyledAttributes(ATTRS);
mDivider = ta.getDrawable(0);
ta.recycle();
setOrientation(Orientation);
}
/**
* 設(shè)置布局走向方法
*/
private void setOrientation(int Orientation){
if (mOrientation !=ORIENTETION_VERTIVAL && mOrientation != ORIENTATION_HORIZONTAL)
throw new IllegalArgumentException("Error Orientation");
mOrientation = Orientation;
}
/**
* 要畫分割線必須得有畫布
* onDraw方法
*/
@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
if (mOrientation == ORIENTETION_VERTIVAL){
drawVertical(c,parent);
}else{
drawHorizontal(c,parent);
}
}
/**
* 橫向
*/
private void drawHorizontal(Canvas c, RecyclerView parent) {
//回去父布局的頂部?jī)?nèi)間距為top
final int top = parent.getPaddingTop();
//由圖可知,利用parent的高度減去底部?jī)?nèi)間距為底
final int buttom = 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 rl = (RecyclerView.LayoutParams) child.getLayoutParams();
//獲取子布局的最右位置+右外間距為右
final int left = child.getRight() + rl.rightMargin;
final int right = left + mDivider.getIntrinsicHeight();
mDivider.setBounds(left,top,right,buttom);
mDivider.draw(c);
}
}
private void drawVertical(Canvas c, RecyclerView parent) {
//parent的左內(nèi)間距為左
final int left = parent.getPaddingLeft();
//parent寬度減去parent的right為右
final int right = parent.getWidth()- parent.getRight();
final int childCount = parent.getChildCount();
for (int i = 0 ; i <childCount ;++i){
final View child = parent.getChildAt(i);
final RecyclerView recyclerView = new RecyclerView(parent.getContext());
final RecyclerView.LayoutParams rl = (RecyclerView.LayoutParams) child.getLayoutParams();
final int top = child.getBottom() + rl.bottomMargin;
final int buttom = top + mDivider.getIntrinsicHeight();
mDivider.setBounds(left,top,right,buttom);
mDivider.draw(c);
}
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
if (mOrientation == ORIENTETION_VERTIVAL){
outRect.set(0,0,0,mDivider.getIntrinsicHeight());
}else{
outRect.set(0,0,mDivider.getIntrinsicWidth(),0);
}
}
}```
- 使用方法很簡(jiǎn)答,只需調(diào)用
addItemDecolation
方法即可
效果
- 如果想更炫的效果可以自己定制以及其他兩個(gè)效果,在這里就不演示了
添加點(diǎn)擊方法
除了分割線有點(diǎn)坑爸爸之外,還有就是并沒有點(diǎn)擊方法的API,所以需要我們自己定制,我們可以在適配器里寫我們的方法給MainActivity調(diào)用,代碼如下:
MyAdapter.java
public class MyAadapter extends RecyclerView.Adapter{
private LayoutInflater inflater;
public List<String> list;
private OnClickListener mOnItemClickListener;
/**
* 回調(diào)
*/
public interface OnClickListener{
public void OnClick(View view,int position);
public boolean OnLongClick(RecyclerView.ViewHolder viewHolder,View view,int position);
}
public void setOnItemClick(OnClickListener mOnItemClickListener){
this.mOnItemClickListener = mOnItemClickListener;
}
public MyAadapter(Context context , List<String> list) {
this.list = list;
inflater = LayoutInflater.from(context);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new ViewHolder(inflater.inflate(R.layout.item_viewholder,parent,false));
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final ViewHolder viewHolder = (ViewHolder) holder;
viewHolder.textview.setText(list.get(position));
//監(jiān)聽回調(diào)
if (mOnItemClickListener != null){
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int pos = viewHolder.getPosition();
mOnItemClickListener.OnClick(viewHolder.itemView,pos);
}
});
viewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
int pos = viewHolder.getPosition();
mOnItemClickListener.OnLongClick(viewHolder,viewHolder.itemView,pos);
return false;
}
});
}
}
@Override
public int getItemCount() {
return list.size();
}
private class ViewHolder extends RecyclerView.ViewHolder{
private TextView textview;
public ViewHolder(View itemView) {
super(itemView);
textview = (TextView) itemView.findViewById(R.id.text_view);
}
}
}```
MainActivity.java
只需在MainActivity中用Adapter調(diào)用方法即可
myAadapter.setOnItemClick(new MyAadapter.OnClickListener() {
@Override
public void OnClick(View view, int position) {
Toast.makeText(MainActivity.this,(position+1)+"onclick",Toast.LENGTH_SHORT).show();
}
@Override
public boolean OnLongClick(RecyclerView.ViewHolder viewHolder,
View view, int position) {
Toast.makeText(MainActivity.this,(position + 1)+"onLongClick",Toast.LENGTH_SHORT).show();
if (position != mDatas.size()-1){
helper.startDrag(viewHolder);
}
return false;
}
});```
效果
基本拓展
如果RecyclerView只是這樣的我選擇狗帶,但事實(shí)肯定不是,不然Google不可能花2W多行代碼實(shí)現(xiàn)RecyclerView.下面開始展示他優(yōu)秀的小功能
- 動(dòng)態(tài)添加移除
以往在ListView我們要添加一項(xiàng)或者移除一項(xiàng)Item,有點(diǎn)難度,不過RecyclerView讓你一步到站,查看文檔可以發(fā)現(xiàn)RecyclerView.Adapter利用兩個(gè)方法notifyItemInserted(position);
,notifyItemRemoved(position);
,就是這兩個(gè)讓我們一步實(shí)現(xiàn)添加移除,我們可以簡(jiǎn)單封裝在我們的適配器Adapter里,利用Toolbar定制兩個(gè)菜單項(xiàng)實(shí)現(xiàn)點(diǎn)擊添加移除
Menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:title="@string/add"
android:id="@+id/id_btn_add"
app:showAsAction="ifRoom"
android:orderInCategory="80" />
<item
android:title="@string/remove"
android:id="@+id/id_btn_remove"
app:showAsAction="ifRoom"
android:orderInCategory="90" />
</menu>```
MyAdapter.java
public void insertOne(int position){
list.add("Insert One");
notifyItemInserted(position);
}
public void removeOne(int position){
list.add("remove One");
notifyItemRemoved(position);
}```
效果
2.拖拽及側(cè)滑刪除
這個(gè)就是這兩天學(xué)習(xí)最酷的一個(gè)功能,它的實(shí)現(xiàn)竟然也很簡(jiǎn)單,只需利用ItemTouchHelper
這個(gè)幫助類即可,新建一個(gè)對(duì)象可以發(fā)現(xiàn),它需要一個(gè)CallBack參數(shù),所以我們寫一個(gè)類擴(kuò)展自ItemTouchHelper.Callback
MyCallBack.java
public class MyCallBack extends ItemTouchHelper.Callback{
private List<String> mDatas;
private MyAadapter adapter;
public MyCallBack(MyAadapter adapter) {
this.adapter = adapter;
this.mDatas = adapter.list;
}
/**
* 此方法用以設(shè)置是否響應(yīng)拖拽或滑動(dòng)事件,并且確定類型
*/
@Override
public int getMovementFlags(RecyclerView recyclerView,
RecyclerView.ViewHolder viewHolder) {
final int dragFlags ,swipFlags;
/**
* 網(wǎng)格方向有UP ,Down ,left,right四個(gè)方向
*/
if (recyclerView.getLayoutManager() instanceof GridLayoutManager){
dragFlags= ItemTouchHelper.UP|
ItemTouchHelper.DOWN|ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT;
swipFlags = 0;
}else{
//LineaLayout只有Up ,Down
dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
//右滑刪除
swipFlags = ItemTouchHelper.END;
}
return makeMovementFlags(dragFlags,swipFlags);
}
@Override
public boolean onMove(RecyclerView recyclerView,
RecyclerView.ViewHolder viewHolder,
RecyclerView.ViewHolder target) {
int framPosition = viewHolder.getAdapterPosition();
int toPosition = target.getAdapterPosition();
/**
* 向上拖拽
*/
if (framPosition > toPosition){
for (int i = framPosition ;i < toPosition;++i){
Collections.swap(mDatas,i,i+1);
}
/**
* 向下拖拽
*/
}else {
for (int i = framPosition ;i > toPosition ;++i){
Collections.swap(mDatas,i,i-1);
}
}
adapter.notifyItemMoved(framPosition,toPosition);
return true;
}
/**
* viewHolder
* params direction表示滑動(dòng)方向,此處我們?cè)谏厦嬉?guī)定為右滑
*/
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
adapter.notifyItemRemoved(position);
adapter.list.remove(position);
}
/**
* 是否長(zhǎng)按拖拽
*/
@Override
public boolean isLongPressDragEnabled() {
return false;
}
}```
接著在MainActivity中我們之前定制的長(zhǎng)按事件中利用ItemTouchHelper的```startDrag(viewHolder)```實(shí)現(xiàn)長(zhǎng)按拖拽滑動(dòng)刪除,代碼如下
``` /**
* 拖拽事件
*/
final ItemTouchHelper helper = new ItemTouchHelper(new MyCallBack(myAadapter));
helper.attachToRecyclerView(recyclerView);
myAadapter.setOnItemClick(new MyAadapter.OnClickListener() {
@Override
public void OnClick(View view, int position) {
Toast.makeText(MainActivity.this,(position+1)+"onclick",Toast.LENGTH_SHORT).show();
}
@Override
public boolean OnLongClick(RecyclerView.ViewHolder viewHolder,
View view, int position) {
Toast.makeText(MainActivity.this,(position + 1)+"onLongClick",Toast.LENGTH_SHORT).show();
if (position != mDatas.size()-1){
helper.startDrag(viewHolder);
}
return false;
}
});```
效果
![drag.gif](http://upload-images.jianshu.io/upload_images/2605454-60ab91d0610e7db9.gif?imageMogr2/auto-orient/strip)
如果這樣簡(jiǎn)單的實(shí)現(xiàn)這么酷的功能還沒愛上它,沒關(guān)系接下來(lái)的學(xué)習(xí)將會(huì)更加炫酷
##### 如果你覺得本文有所錯(cuò)漏,麻煩指出,相互交流共同進(jìn)步.