快速掌握 Recyclerview、SwipeRefreshLayout斯辰、Cardview

一舶担、Recyclerview


1.簡介

Recyclerview是Android 5.0新增的一個列表控件。顧名思義彬呻,recycler view衣陶,只負責回收和復用視圖,高度的解耦闸氮,可靈活定制剪况,輕松實現(xiàn)Listview、GridView蒲跨、瀑布流的效果译断。

優(yōu)點:

  • item復用
    把ViewHolder的實現(xiàn)封裝起來,規(guī)范了ViewHolder或悲,把item的view寫入ViewHolder中孙咪,可以通過復用ViewHolder來實現(xiàn)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.創(chuàng)建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,創(chuàng)建不同的viewholder男公,綁定不同的數(shù)據(jù)杨蛋。

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);
// 創(chuàng)建布局管理器,實現(xiàn)listview效果
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
// 設置布局管理器
mRecyclerView.setLayoutManager(linearLayoutManager);
// 確定item的大小是固定的理澎,設置為true,recyclerview可以得到優(yōu)化
mRecyclerView.setHasFixedSize(true);
// 添加分割線
mRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
// 適配器
mAdapter = new SimpleAdapter(this,mDatas);
// 設置適配器
mRecyclerView.setAdapter(mAdapter);
image

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

使用示例
注意:數(shù)據(jù)源順序是A-z

LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,true);
image
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false);
image

2.GridLayoutManager

Gridview效果糠爬,網(wǎng)格列表

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

使用示例
注意:數(shù)據(jù)源順序是A-z

GridLayoutManager gridLayoutManager = new GridLayoutManager(this,4, OrientationHelper.VERTICAL,true);
image
GridLayoutManager gridLayoutManager = new GridLayoutManager(this,4, OrientationHelper.HORIZONTAL,false);
image

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(填充滿行高)执隧,寬度隨機生成高度,為了區(qū)分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);
image

豎向瀑布流

  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);
image

發(fā)現(xiàn)問題:
可以看到,當來回滑動時蕊唐,瀑布流中的item的高度屋摔、位置都會發(fā)生變化,這是因為在onCreateViewHolder()中設置的item的高度替梨,當來回滑動钓试,item被回收復用時装黑,重新走onCreateViewHolder(),又會重新生成高度弓熏,導致高度恋谭、位置變化。 真實項目中挽鞠,這個問題不應該發(fā)生疚颊,列表中的數(shù)據(jù)是不變的,由數(shù)據(jù)生成的item高度也不會變化信认,位置就不會變化材义。

解決上面的問題,給每個item固定的高度狮杨。
1.Adapter構(gòu)造中生成高度

 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);
}
image

4.ItemDecoration

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

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

DividerItemDecoration算是v7包中提供的一個分割線的示例吧,繼承自 RecyclerView.ItemDecoration橄教,在構(gòu)造方法中讀取系統(tǒng)屬性android:listDivider,獲取到一個drawable對象清寇,繪制出來,支持橫向护蝶、豎向华烟。

image

我們可以覆蓋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>
image

我們也可以在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;
}
image

可以看到,我們使用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單獨設置點擊、長按事件刽沾。


image

二本慕、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);

    // 刷新監(jiān)聽
    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);
            }
        }
    };
image

三鉴象、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>
image

3. 常用屬性

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

4. 點擊水波紋效果

測試過傍睹,給android:background app:cardBackgroundColor設置選擇器都無效。

設置屬性

android:foreground="?attr/selectableItemBackground"

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

image

image

自定義前景色
1.在drawable中創(chuàng)建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>
image

2.在drawable-v21中創(chuàng)建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"/>
image

GitHub示例:ViewDemo/RecyclerviewDemo


個人總結(jié),水平有限腊脱,如果有錯誤访得,希望大家能給留言指正!如果對您有所幫助陕凹,可以幫忙點個贊悍抑!如果轉(zhuǎn)載,希望可以留言告知并在顯著位置保留草帽團長的署名和標明文章出處杜耙!最后搜骡,非常感謝您的閱讀!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末佑女,一起剝皮案震驚了整個濱河市记靡,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌团驱,老刑警劉巖摸吠,帶你破解...
    沈念sama閱讀 218,546評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異嚎花,居然都是意外死亡寸痢,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評論 3 395
  • 文/潘曉璐 我一進店門贩幻,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人两嘴,你說我怎么就攤上這事丛楚。” “怎么了憔辫?”我有些...
    開封第一講書人閱讀 164,911評論 0 354
  • 文/不壞的土叔 我叫張陵趣些,是天一觀的道長。 經(jīng)常有香客問我贰您,道長坏平,這世上最難降的妖魔是什么拢操? 我笑而不...
    開封第一講書人閱讀 58,737評論 1 294
  • 正文 為了忘掉前任舶替,我火速辦了婚禮令境,結(jié)果婚禮上弥鹦,老公的妹妹穿的比我還像新娘。我一直安慰自己爷辙,他們只是感情好彬坏,可當我...
    茶點故事閱讀 67,753評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著犬钢,像睡著了一般苍鲜。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上玷犹,一...
    開封第一講書人閱讀 51,598評論 1 305
  • 那天混滔,我揣著相機與錄音,去河邊找鬼歹颓。 笑死坯屿,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的巍扛。 我是一名探鬼主播领跛,決...
    沈念sama閱讀 40,338評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼撤奸!你這毒婦竟也來了吠昭?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,249評論 0 276
  • 序言:老撾萬榮一對情侶失蹤胧瓜,失蹤者是張志新(化名)和其女友劉穎矢棚,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體府喳,經(jīng)...
    沈念sama閱讀 45,696評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡蒲肋,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,888評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片兜粘。...
    茶點故事閱讀 40,013評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡申窘,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出孔轴,到底是詐尸還是另有隱情剃法,我是刑警寧澤,帶...
    沈念sama閱讀 35,731評論 5 346
  • 正文 年R本政府宣布距糖,位于F島的核電站玄窝,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏悍引。R本人自食惡果不足惜恩脂,卻給世界環(huán)境...
    茶點故事閱讀 41,348評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望趣斤。 院中可真熱鬧俩块,春花似錦、人聲如沸浓领。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,929評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽联贩。三九已至漫仆,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間泪幌,已是汗流浹背盲厌。 一陣腳步聲響...
    開封第一講書人閱讀 33,048評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留祸泪,地道東北人吗浩。 一個月前我還...
    沈念sama閱讀 48,203評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像没隘,于是被迫代替她去往敵國和親懂扼。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,960評論 2 355