天天看點

學習筆記:Recyclerview、SwipeRefreshLayout、Cardview的使用

一、Recyclerview

1.簡介

Recyclerview是Android 5.0新增的一個清單控件。顧名思義,recycler view,隻負責回收和複用視圖,高度的解耦,可靈活定制,輕松實作Listview、GridView、瀑布流的效果。

優點:

  • item複用

    把ViewHolder的實作封裝起來,規範了ViewHolder,把item的view寫入ViewHolder中,可以通過複用ViewHolder來實作view的複用

  • 靈活、可定制化高、可拓展性高
  1. 顯示方式:通過LayoutManager控制
  2. item分割線:通過ItemDecoration控制
  3. item動畫:通過ItemAnimator控制
  4. item點選事件:自定義

2.基本使用

1.添加依賴

compile 'com.android.support:recyclerview-v7:25.3.1'
           

2.xml引用

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context="com.strivestay.viewdemo.MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </android.support.v7.widget.RecyclerView>

</LinearLayout>

           

3.建立item布局檔案和擴充卡

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="72dp"
    android:orientation="vertical"
    android:background="#44ff0000">

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:layout_gravity="center"/>
</FrameLayout>
           
package com.strivestay.viewdemo;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

/**
 * recyclerview擴充卡
 *
 * @author StriveStay
 * @date 2017/12/8
 */
public class SimpleAdapter extends RecyclerView.Adapter<SimpleAdapter.ItemViewHolder> {
    private List<String> mdatas;
    private LayoutInflater mInflater;
    private Context mContext;

    public SimpleAdapter(Context context, List<String> data) {
        this.mContext = context;
        this.mInflater = LayoutInflater.from(context);
        this.mdatas = data;
    }

    @Override
    public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.item_recycler, parent, false);
        return new ItemViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ItemViewHolder holder, int position) {
        holder.mTv.setText(mdatas.get(position));
    }

    @Override
    public int getItemCount() {
        return mdatas.size();
    }


    class ItemViewHolder extends RecyclerView.ViewHolder {
        TextView mTv;

        public ItemViewHolder(View itemView) {
            super(itemView);
            mTv = (TextView) itemView.findViewById(R.id.tv);
        }
    }
}

           

如果有多種類型的item,則我們繼承時是這樣的

RecyclerView.Adapter<RecyclerView.ViewHolder>

,然後重寫

getItemViewType()

方法傳回不同的item type,建立不同的viewholder,綁定不同的資料。

4.Recyclerview設定

private void initData() {
    mDatas = new ArrayList<>();
    
    for (int i = 'A'; i < 'z'; i++) {
        mDatas.add(""+(char)i);
        L.e(i+"=="+(char)i);
    }
}
           
// 擷取recyclerview
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
// 建立布局管理器,實作listview效果
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
// 設定布局管理器
mRecyclerView.setLayoutManager(linearLayoutManager);
// 确定item的大小是固定的,設定為true,recyclerview可以得到優化
mRecyclerView.setHasFixedSize(true);
// 添加分割線
mRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
// 擴充卡
mAdapter = new SimpleAdapter(this,mDatas);
// 設定擴充卡
mRecyclerView.setAdapter(mAdapter);
           
學習筆記:Recyclerview、SwipeRefreshLayout、Cardview的使用

3.LayoutManager 布局管理器

1.LinearLayoutManager

Listview效果,普通清單

public LinearLayoutManager(@Nullable android.content.Context context,

int orientation,

boolean reverseLayout)

Parameters:

context: Current context, will be used to access resources.

orientation: Layout orientation. Should be HORIZONTAL or VERTICAL.

預設為VERTICAL

reverseLayout: When set to true, layouts from end to start.

預設false

使用示例

注意:資料源順序是A-z

LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,true);
           
學習筆記:Recyclerview、SwipeRefreshLayout、Cardview的使用
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false);
           
學習筆記:Recyclerview、SwipeRefreshLayout、Cardview的使用

2.GridLayoutManager

Gridview效果,網格清單

public GridLayoutManager(@Nullable android.content.Context context,

int spanCount,

int orientation,

boolean reverseLayout)

Parameters:

context: Current context, will be used to access resources.

spanCount: The number of columns or rows in the grid.

當orientaion == VERTICAL時,代表columns; orientaion == VERTICAL,代表rows

orientation: Layout orientation. Should be HORIZONTAL or VERTICAL.

預設VERTICAL

reverseLayout: When set to true, layouts from end to start.

預設false

使用示例

注意:資料源順序是A-z

GridLayoutManager gridLayoutManager = new GridLayoutManager(this,4, OrientationHelper.VERTICAL,true);
           
學習筆記:Recyclerview、SwipeRefreshLayout、Cardview的使用
GridLayoutManager gridLayoutManager = new GridLayoutManager(this,4, OrientationHelper.HORIZONTAL,false);
           
學習筆記:Recyclerview、SwipeRefreshLayout、Cardview的使用

3.StaggeredGridLayoutManager

瀑布流

public StaggeredGridLayoutManager(int spanCount,

int orientation)

Parameters:

spanCount: If orientation is vertical, spanCount is number of columns. If orientation is horizontal, spanCount is number of rows.

orientation: VERTICAL or HORIZONTAL

使用示例

橫向瀑布流

1.item高度match_parent(填充滿行高),寬度随機生成高度,為了區分item邊界,加入margin

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#44ff0000"
    android:layout_margin="3dp">
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:layout_gravity="center"/>
</FrameLayout>
           
@Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = mInflater.inflate(R.layout.item_recycler, parent, false);
    view.getLayoutParams().width = new Random().nextInt(150) + 50;
    return new ItemViewHolder(view);
}
           

2.使用StaggeredGridLayoutManager

StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(4,StaggeredGridLayoutManager.HORIZONTAL);
           
學習筆記:Recyclerview、SwipeRefreshLayout、Cardview的使用

豎向瀑布流

  1. item 寬度match_parent(占滿列寬),高度随機生成,同樣加margin
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#44ff0000"
    android:layout_margin="3dp">
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:layout_gravity="center"/>
</FrameLayout>
           
@Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = mInflater.inflate(R.layout.item_recycler, parent, false);
    view.getLayoutParams().height = new Random().nextInt(150) + 50;
    return new ItemViewHolder(view);
}
           

2.使用StaggeredGridLayoutManager

StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(4,StaggeredGridLayoutManager.VERTICAL);
           
學習筆記:Recyclerview、SwipeRefreshLayout、Cardview的使用

發現問題:

可以看到,當來回滑動時,瀑布流中的item的高度、位置都會發生變化,這是因為在onCreateViewHolder()中設定的item的高度,當來回滑動,item被回收複用時,重新走onCreateViewHolder(),又會重新生成高度,導緻高度、位置變化。 真實項目中,這個問題不應該發生,清單中的資料是不變的,由資料生成的item高度也不會變化,位置就不會變化。

解決上面的問題,給每個item固定的高度。

1.Adapter構造中生成高度

public SimpleAdapter(Context context, List<String> data) {
        this.mContext = context;
        this.mInflater = LayoutInflater.from(context);
        this.mdatas = data;

        mHeights = new ArrayList<>();
        for (int i = 0; i < mdatas.size(); i++) {
            mHeights.add(new Random().nextInt(150) + 50);
        }
           

2.設定高度

@Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
    holder.mTv.setText(mdatas.get(position));
    holder.itemView.getLayoutParams().height = mHeights.get(position);
}
           
學習筆記:Recyclerview、SwipeRefreshLayout、Cardview的使用

4.ItemDecoration

在基本使用中,我們看到有這樣一行代碼:添加分割線

mRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
           

DividerItemDecoration算是v7包中提供的一個分割線的示例吧,繼承自 RecyclerView.ItemDecoration,在構造方法中讀取系統屬性

android:listDivider

,擷取到一個drawable對象,繪制出來,支援橫向、豎向。

學習筆記:Recyclerview、SwipeRefreshLayout、Cardview的使用

我們可以覆寫

android:listDivider

屬性,自定義drawable圖檔

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:listDivider">@drawable/divider_recycler</item>
</style>
           
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <gradient
        android:centerColor="#00ff00"
        android:endColor="#0000ff"
        android:startColor="#ff0000"
        android:type="linear">
    </gradient>
    <size
        android:height="5dp" android:width="5dp">
    </size>
</shape>
           
學習筆記:Recyclerview、SwipeRefreshLayout、Cardview的使用

我們也可以在item的布局檔案中加入分隔線,或者使用margin來空出分隔線。

5.ItemAnimation

Recyclerview添加、删除時的動畫效果,提供一個預設的動畫效果DefaultItemAnimator。

mRecyclerView.setItemAnimator(new DefaultItemAnimator());
           
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case R.id.menu_add:
            mDatas.add(1,"新增條目");
            mAdapter.notifyDataSetChanged(); // 沒有動畫效果
            break;
        case R.id.menu_delete:
            mDatas.remove(1);
            mAdapter.notifyItemRemoved(1);
            break;
    }

    return true;
}
           
學習筆記:Recyclerview、SwipeRefreshLayout、Cardview的使用

可以看到,我們使用notifyDataSetChanged()這種全局重新整理方法是沒有動畫效果的,使用notifyItemInserted、notifyItemRangeInserted、notifyItemRemoved這些局部重新整理有動畫效果的。

6. item點選事件

感覺最簡單的方式就是在Adapter中的onBindViewholder()中設定,如下:

@Override
    public void onBindViewHolder(ItemViewHolder holder, final int position) {
        holder.mTv.setText(mdatas.get(position));
       // item點選事件
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(mContext, "點選了"+mdatas.get(position), Toast.LENGTH_SHORT).show();
            }
        });
        // item長按事件
        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Toast.makeText(mContext, "長按了"+mdatas.get(position), Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }
           

同樣可以為item中的child view單獨設定點選、長按事件。

學習筆記:Recyclerview、SwipeRefreshLayout、Cardview的使用

二、SwipeRefreshLayout

1. 簡介

SwipeRefreshLayout是v4包中提供的一個下拉重新整理控件,繼承自Viewgroup,隻支援一個直接的child view,通常與recyclerview搭配使用。

2. 基本使用

1.添加依賴(AS自動添加v7依賴,包含v4)

compile 'com.android.support:appcompat-v7:25.3.1'
           

2.xml引用

<android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swiperefresh_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        </android.support.v7.widget.RecyclerView>

    </android.support.v4.widget.SwipeRefreshLayout>
           

3.設定

private void initSwipeRefreshLayout() {
    // 擷取swiperefreshlayout
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swiperefresh_layout);
    // 設定進度條顔色
    mSwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
            android.R.color.holo_green_light, android.R.color.holo_orange_light,
            android.R.color.holo_red_light);
    // 設定進度條背景色
    mSwipeRefreshLayout.setProgressBackgroundColorSchemeResource(android.R.color.black);

    // 重新整理監聽
    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mDatas.add(1,"重新整理");
            mAdapter.notifyItemInserted(1);

            mHandler.sendEmptyMessageDelayed(0,1000);

        }
    });
}
           
Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // 是否正在重新整理
            if(mSwipeRefreshLayout.isRefreshing()){
                // 停止重新整理
                mSwipeRefreshLayout.setRefreshing(false);
            }
        }
    };
           
學習筆記:Recyclerview、SwipeRefreshLayout、Cardview的使用

三、Cardview

1. 簡介

Cardview,顧名思義,卡片式視圖,是5.0提供的MD風格控件,繼承自FrameLayout。

2. 基本使用

1. 添加依賴

compile 'com.android.support:cardview-v7:25.3.1'
           

2. xml引用

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="72dp"
    android:layout_margin="5dp"
    app:cardBackgroundColor="#ffffff"
    app:cardCornerRadius="8dp"
    app:cardElevation="5dp">

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textSize="16sp"/>
    
</android.support.v7.widget.CardView>
           
學習筆記:Recyclerview、SwipeRefreshLayout、Cardview的使用

3. 常用屬性

屬性 作用
app:cardBackgroundColor 背景顔色
app:cardCornerRadius 圓角大小
app:cardElevation Z軸陰影大小
app:cardMaxElevation Z軸最大高度值
app:cardUseCompatPadding 是否使用CompatPadding,V21+的版本和之前的版本仍舊具有一樣的計算方式
app:cardPreventCornerOverlap 是否使用PreventCornerOverlap,在V20和之前的版本中添加内邊距,這個屬性為了防止内容和邊角的重疊
app:contentPadding 内容的padding
app:contentPaddingLeft 内容左padding
app:contentPaddingTop 内容上padding
app:contentPaddingRight 内容右padding
app:contentPaddingBottom 内容下padding

4. 點選水波紋效果

測試過,給

android:background

app:cardBackgroundColor

設定選擇器都無效。

設定屬性

android:foreground="?attr/selectableItemBackground"
           

5.0及以上有水波紋,5.0以下前景色改變

學習筆記:Recyclerview、SwipeRefreshLayout、Cardview的使用
學習筆記:Recyclerview、SwipeRefreshLayout、Cardview的使用

自定義前景色

1.在drawable中建立foreground_item.xml,相容5.0以下

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:drawable="@color/red" android:state_pressed="true" />
    <item android:drawable="@android:color/transparent" />
</selector>
           
學習筆記:Recyclerview、SwipeRefreshLayout、Cardview的使用

2.在drawable-v21中建立foreground_item.xml,用于5.0以上水波紋效果

<?xml version="1.0" encoding="utf-8"?>
<ripple
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="#ff00ff"/>
           
學習筆記:Recyclerview、SwipeRefreshLayout、Cardview的使用
個人總結,水準有限,如果有錯誤,希望大家能給留言指正!如果對您有所幫助,可以幫忙點個贊!如果轉載,希望可以标明文章出處!最後,非常感謝您的閱讀!