本文圖片接口來自干貨集中營http://gank.io/api
RecyclerView是support.v7包中的控件躯嫉,可以說是ListView和GridView的增強升級版癌压。
官方對RecyclerView的描述是(不翻譯不是因為我英語差啊屉符,真的):
A flexible view for providing a limited window into a large data set.
RecyclerView從2014年發(fā)布到現(xiàn)在已經很長時間了硫兰,使用已經相當普遍。
本文主要介紹了RecyclerView的基礎使用、自動加載更多數(shù)據(jù)、item的拖拽和劃動刪除详恼。詳細效果和使用請看我的demo;
RecyclerView基礎用法##
RecyclerView的用法和ListView類似。我用網格布局為例引几,先上代碼再細說昧互。
首先在布局中要創(chuàng)建這個控件:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
android:id="@+id/grid_coordinatorLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:background="#ffffff"
tools:context="com.zcp.recyclerviewddmo.GridActivity">
<!--工具欄-->
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
/>
</android.support.design.widget.AppBarLayout>
<!--下拉刷新控件-->
<android.support.v4.widget.SwipeRefreshLayout
android:id="@+id/grid_swipe_refresh"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
>
<!--本文主角-->
<android.support.v7.widget.RecyclerView
android:id="@+id/grid_recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</android.support.v4.widget.SwipeRefreshLayout>
</android.support.design.widget.CoordinatorLayout>
Activity的代碼如下:
public class GridActivity extends AppCompatActivity {
private static RecyclerView recyclerview;
private CoordinatorLayout coordinatorLayout;
private GridAdapter mAdapter;
private List<Meizi> meizis;
private GridLayoutManager mLayoutManager;
private int lastVisibleItem ;
private int page=1;
private ItemTouchHelper itemTouchHelper;
private SwipeRefreshLayout swipeRefreshLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initView();//初始化布局
setListener();//設置監(jiān)聽事件
//執(zhí)行加載數(shù)據(jù)
new GetData().execute("http://gank.io/api/data/福利/10/1");
}
private void initView(){
coordinatorLayout=(CoordinatorLayout)findViewById(R.id.grid_coordinatorLayout);
recyclerview=(RecyclerView)findViewById(R.id.grid_recycler);
mLayoutManager=new GridLayoutManager(GridActivity.this,3,GridLayoutManager.VERTICAL,false);//設置為一個3列的縱向網格布局
recyclerview.setLayoutManager(mLayoutManager);
swipeRefreshLayout=(SwipeRefreshLayout) findViewById(R.id.grid_swipe_refresh) ;
//調整SwipeRefreshLayout的位置
swipeRefreshLayout.setProgressViewOffset(false, 0, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, getResources().getDisplayMetrics()));
}
private void setListener(){
//swipeRefreshLayout刷新監(jiān)聽
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
page=1;
new GetData().execute("http://gank.io/api/data/福利/10/1");
}
});
}
private class GetData extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
//設置swipeRefreshLayout為刷新狀態(tài)
swipeRefreshLayout.setRefreshing(true);
}
@Override
protected String doInBackground(String... params) {
return MyOkhttp.get(params[0]);
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(!TextUtils.isEmpty(result)){
JSONObject jsonObject;
Gson gson=new Gson();
String jsonData=null;
try {
jsonObject = new JSONObject(result);
jsonData = jsonObject.getString("results");
} catch (JSONException e) {
e.printStackTrace();
}
if(meizis==null||meizis.size()==0){
meizis= gson.fromJson(jsonData, new TypeToken<List<Meizi>>() {}.getType());
Meizi pages=new Meizi();
pages.setPage(page);
meizis.add(pages);//在數(shù)據(jù)鏈表中加入一個用于顯示頁數(shù)的item
}else{
List<Meizi> more= gson.fromJson(jsonData, new TypeToken<List<Meizi>>() {}.getType());
meizis.addAll(more);
Meizi pages=new Meizi();
pages.setPage(page);
meizis.add(pages);//在數(shù)據(jù)鏈表中加入一個用于顯示頁數(shù)的item
}
if(mAdapter==null){
recyclerview.setAdapter(mAdapter = new GridAdapter(GridActivity.this,meizis));//recyclerview設置適配器
//實現(xiàn)適配器自定義的點擊監(jiān)聽
mAdapter.setOnItemClickListener(new GridAdapter.OnRecyclerViewItemClickListener() {
@Override
public void onItemClick(View view) {
int position=recyclerview.getChildAdapterPosition(view);
SnackbarUtil.ShortSnackbar(coordinatorLayout,"點擊第"+position+"個",SnackbarUtil.Info).show();
//彩色Snackbar工具類,請看我之前的文章《沒時間解釋了伟桅,快使用Snackbar!——Android Snackbar花式使用指南》http://www.reibang.com/p/cd1e80e64311
}
@Override
public void onItemLongClick(View view) {
}
});
}else{
//讓適配器刷新數(shù)據(jù)
mAdapter.notifyDataSetChanged();
}
}
//停止swipeRefreshLayout加載動畫
swipeRefreshLayout.setRefreshing(false);
}
}
}
接下來我們看RecyclerView的適配器:
public class GridAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements View.OnClickListener, View.OnLongClickListener {
private Context mContext;
private List<Meizi> datas;//數(shù)據(jù)
//自定義監(jiān)聽事件
public static interface OnRecyclerViewItemClickListener {
void onItemClick(View view);
void onItemLongClick(View view);
}
private OnRecyclerViewItemClickListener mOnItemClickListener = null;
public void setOnItemClickListener(OnRecyclerViewItemClickListener listener) {
mOnItemClickListener = listener;
}
//適配器初始化
public GridAdapter(Context context,List<Meizi> datas) {
mContext=context;
this.datas=datas;
}
@Override
public int getItemViewType(int position) {
//判斷item類別敞掘,是圖還是顯示頁數(shù)(圖片有URL)
if (!TextUtils.isEmpty(datas.get(position).getUrl())) {
return 0;
} else {
return 1;
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
//根據(jù)item類別加載不同ViewHolder
if(viewType==0){
View view = LayoutInflater.from(mContext
).inflate(R.layout.grid_meizi_item, parent,
false);//這個布局就是一個imageview用來顯示圖片
MyViewHolder holder = new MyViewHolder(view);
//給布局設置點擊和長點擊監(jiān)聽
view.setOnClickListener(this);
view.setOnLongClickListener(this);
return holder;
}else{
MyViewHolder2 holder2=new MyViewHolder2(LayoutInflater.from(
mContext).inflate(R.layout.page_item, parent,
false));//這個布局就是一個textview用來顯示頁數(shù)
return holder2;
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
//將數(shù)據(jù)與item視圖進行綁定,如果是MyViewHolder就加載網絡圖片贿讹,如果是MyViewHolder2就顯示頁數(shù)
if(holder instanceof MyViewHolder){
Picasso.with(mContext).load(datas.get(position).getUrl()).into(((MyViewHolder) holder).iv);//加載網絡圖片
}else if(holder instanceof MyViewHolder2){
((MyViewHolder2) holder).tv.setText(datas.get(position).getPage()+"頁");
}
}
@Override
public int getItemCount()
{
return datas.size();//獲取數(shù)據(jù)的個數(shù)
}
//點擊事件回調
@Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(v);
}
}
@Override
public boolean onLongClick(View v) {
if (mOnItemClickListener!= null) {
mOnItemClickListener.onItemLongClick(v);
}
return false;
}
//自定義ViewHolder渐逃,用于加載圖片
class MyViewHolder extends RecyclerView.ViewHolder
{
private ImageButton iv;
public MyViewHolder(View view)
{
super(view);
iv = (ImageButton) view.findViewById(R.id.iv);
}
}
//自定義ViewHolder,用于顯示頁數(shù)
class MyViewHolder2 extends RecyclerView.ViewHolder
{
private TextView tv;
public MyViewHolder2(View view)
{
super(view);
tv = (TextView) view.findViewById(R.id.tv);
}
}
//添加一個item
public void addItem(Meizi meizi, int position) {
meizis.add(position, meizi);
notifyItemInserted(position);
recyclerview.scrollToPosition(position);//recyclerview滾動到新加item處
}
//刪除一個item
public void removeItem(final int position) {
meizis.remove(position);
notifyItemRemoved(position);
}
}
數(shù)據(jù)類:
public class Meizi {
private String url;//圖片地址
private int page;//頁數(shù)
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
}
RecyclerView的使用和ListView很像吧民褂。
RecyclerView需要通過setLayoutManager()方法設置布局管理器,RecyclerView有三個默認布局管理器LinearLayoutManager疯潭、GridLayoutManager赊堪、StaggeredGridLayoutManager,都支持橫向和縱向排列以及反向滑動竖哩。如果想把RecyclerView改為橫向滑動哭廉,也可以通過調用
mLayoutManager.setOrientation(GridLayoutManager.HORIZONTAL);
RecyclerView不像ListView一樣提供item的點擊監(jiān)聽,所以我們只能自己實現(xiàn)相叁。RecyclerView的item點擊事件監(jiān)聽可以向我本文中為item的view設置監(jiān)聽遵绰,也可以在recyclerView.addOnItemTouchListener里去判斷手勢來實現(xiàn)。
通過調用如下方法可以設置item加載或移除時的動畫
recyclerView.setItemAnimator(new DefaultItemAnimator());
更多的動畫效果可以看別人寫的RecyclerViewItemAnimators 這個項目增淹。
自動加載更多##
要想實現(xiàn)滑動到列表某處時自動加載下一頁(比如剩最后兩個item時)椿访,可以通過對RecyclerView設置滑動監(jiān)聽,獲取當前顯示的最后一個item在適配器中的位置虑润,如果該item的位置小于或等于適配器item總個數(shù)減2成玫,就加載下一頁數(shù)據(jù)。
GridLayoutManager和LinearLayoutManager時方法如下:
//recyclerview滾動監(jiān)聽
recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
//0:當前屏幕停止?jié)L動;1時:屏幕在滾動 且 用戶仍在觸碰或手指還在屏幕上哭当;2時:隨用戶的操作猪腕,屏幕上產生的慣性滑動;
// 滑動狀態(tài)停止并且剩余少于兩個item時钦勘,自動加載下一頁
if (newState == RecyclerView.SCROLL_STATE_IDLE
&& lastVisibleItem +2>=mLayoutManager.getItemCount()) {
new GetData().execute("http://gank.io/api/data/福利/10/"+(++page));
}
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
//獲取加載的最后一個可見視圖在適配器的位置陋葡。
lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();
}
});
StaggeredGridLayoutManager因為item的位置是交錯的,findLastVisibleItemPosition()方法返回的是一個數(shù)組彻采,所以我們得先判斷下這個數(shù)組的最大值腐缤,上面的onScrolled方法寫成這樣
int[] positions= mLayoutManager.findLastVisibleItemPositions(null);
lastVisibleItem =Math.max(positions[0],positions[1]);//根據(jù)StaggeredGridLayoutManager設置的列數(shù)來定
XRecyclerView是別人寫的一個庫,實現(xiàn)了RecyclerView的下拉頭和底部加載布局颊亮,需要的可以看下柴梆。
Item拖拽和滑動刪除##
ItemTouchHelper是一個處理RecyclerView的滑動刪除和拖拽的輔助類,RecyclerView 的item拖拽移動和滑動刪除就靠它來實現(xiàn)终惑。
ItemTouchHelper的監(jiān)聽如下
itemTouchHelper=new ItemTouchHelper(new ItemTouchHelper.Callback() {
//用于設置拖拽和滑動的方向
@Override
public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
int dragFlags=0,swipeFlags=0;
if(recyclerView.getLayoutManager() instanceof StaggeredGridLayoutManager||recyclerView.getLayoutManager() instanceof GridLayoutManager){
//網格式布局有4個方向
dragFlags=ItemTouchHelper.UP|ItemTouchHelper.DOWN|ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT;
}else if(recyclerView.getLayoutManager() instanceof LinearLayoutManager){
//線性式布局有2個方向
dragFlags=ItemTouchHelper.UP|ItemTouchHelper.DOWN;
swipeFlags = ItemTouchHelper.START|ItemTouchHelper.END; //設置側滑方向為從兩個方向都可以
}
return makeMovementFlags(dragFlags,swipeFlags);//swipeFlags 為0的話item不滑動
}
//長摁item拖拽時會回調這個方法
@Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
int from=viewHolder.getAdapterPosition();
int to=target.getAdapterPosition();
Meizi moveItem=meizis.get(from);
meizis.remove(from);
meizis.add(to,moveItem);//交換數(shù)據(jù)鏈表中數(shù)據(jù)的位置
mAdapter.notifyItemMoved(from,to);//更新適配器中item的位置
return true;
}
@Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
//這里處理滑動刪除
}
@Override
public boolean isLongPressDragEnabled() {
return false;//返回true則為所有item都設置可以拖拽
}
});
itemTouchHelper需要與recyclerView綁定才有效果绍在,在recyclerView初始化的時候調用
itemTouchHelper.attachToRecyclerView(recyclerview);
因為我想要網格布局中的圖片item可拖拽,而頁數(shù)item不可拖拽雹有,所以我isLongPressDragEnabled()方法返回的false偿渡,而在item的長點擊事件監(jiān)聽中做具體處理。
mAdapter.setOnItemClickListener(new GridAdapter.OnRecyclerViewItemClickListener() {
@Override
public void onItemClick(View view) {
}
@Override
public void onItemLongClick(View view) {
itemTouchHelper.startDrag(recyclerview.getChildViewHolder(view));//設置拖拽item
}
});
如果你想為item設置拖拽和滑動時的響應動畫效果霸奕,可以利用ItemTouchHelper的下面三個方法溜宽。用線性布局示例:
//當item拖拽開始時調用
@Override
public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
super.onSelectedChanged(viewHolder, actionState);
if(actionState==ItemTouchHelper.ACTION_STATE_DRAG){
viewHolder.itemView.setBackgroundColor(Color.LTGRAY);//拖拽時設置背景色為灰色
}
}
//當item拖拽完成時調用
@Override
public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
super.clearView(recyclerView, viewHolder);
viewHolder.itemView.setBackgroundColor(Color.WHITE);//拖拽停止時設置背景色為白色
}
//當item視圖變化時調用
@Override
public void onChildDraw(Canvas c, RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
//根據(jù)item滑動偏移的值修改item透明度。screenwidth是我提前獲得的屏幕寬度
viewHolder.itemView.setAlpha(1-Math.abs(dX)/screenwidth);
}
本文送給說“三百六十行质帅,行行出碼農”适揉,然后來跟我搶飯碗的兩位兄弟。
我知道你們都喜歡看妹子 →_→...
大家覺得本文還行的話請點個贊n(≧▽≦)n