一舶担、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的復用靈活、可定制化高巡语、可拓展性高
- 顯示方式:通過LayoutManager控制
- item分割線:通過ItemDecoration控制
- item動畫:通過ItemAnimator控制
- 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);
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);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false);
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);
GridLayoutManager gridLayoutManager = new GridLayoutManager(this,4, OrientationHelper.HORIZONTAL,false);
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);
豎向瀑布流
- 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);
發(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);
}
4.ItemDecoration
在基本使用中母截,我們看到有這樣一行代碼:添加分割線
mRecyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
DividerItemDecoration算是v7包中提供的一個分割線的示例吧,繼承自 RecyclerView.ItemDecoration橄教,在構(gòu)造方法中讀取系統(tǒng)屬性android:listDivider
,獲取到一個drawable對象清寇,繪制出來,支持橫向护蝶、豎向华烟。
我們可以覆蓋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>
我們也可以在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;
}
可以看到,我們使用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單獨設置點擊、長按事件刽沾。
二本慕、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);
}
}
};
三鉴象、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>
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以下前景色改變
自定義前景色
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>
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"/>
GitHub示例:ViewDemo/RecyclerviewDemo
個人總結(jié),水平有限腊脱,如果有錯誤访得,希望大家能給留言指正!如果對您有所幫助陕凹,可以幫忙點個贊悍抑!如果轉(zhuǎn)載,希望可以留言告知并在顯著位置保留草帽團長的署名和標明文章出處杜耙!最后搜骡,非常感謝您的閱讀!