(一)前言:
RecyclerView 是Android L版本中新添加的一個(gè)用來(lái)取代ListView的SDK,它的靈活性與可替代性比listview更好漆枚。
(二)介紹:
RecyclerView與ListView原理是類(lèi)似的:都是僅僅維護(hù)少量的View并且可以展示大量的數(shù)據(jù)集湿蛔。RecyclerView用以下兩種方式簡(jiǎn)化了數(shù)據(jù)的展示和處理:
- ①使用LayoutManager來(lái)確定每一個(gè)item的排列方式榆骚。
- ②為增加和刪除項(xiàng)目提供默認(rèn)的動(dòng)畫(huà)效果。
你也可以定義你自己的LayoutManager和添加刪除動(dòng)畫(huà)煌集,RecyclerView項(xiàng)目結(jié)構(gòu)如下:
Adapter:使用RecyclerView之前妓肢,你需要一個(gè)繼承自RecyclerView.Adapter的適配器,作用是將數(shù)據(jù)與每一個(gè)item的界面進(jìn)行綁定苫纤。
LayoutManager:用來(lái)確定每一個(gè)item如何進(jìn)行排列擺放碉钠,何時(shí)展示和隱藏【砭校回收或重用一個(gè)View的時(shí)候喊废,LayoutManager會(huì)向適配器請(qǐng)求新的數(shù)據(jù)來(lái)替換舊的數(shù)據(jù),這種機(jī)制避免了創(chuàng)建過(guò)多的View和頻繁的調(diào)用findViewById方法(與ListView原理類(lèi)似)栗弟。
(三)用法:
1污筷、如果你用的是Android Studio,必須添加依賴(lài)庫(kù):
2乍赫、編寫(xiě)代碼:
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/swipeRefreshLayout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</android.support.v4.widget.SwipeRefreshLayout>
這里我根布局是SwipeRefreshLayout瓣蛀,你們可以不管他(ps:你換你自己的布局就可以,主要接下來(lái)文章我打算寫(xiě)SwipeRefreshLayout與Viewpager滑動(dòng)沖突)雷厂,主要看RecyclerView惋增。
然后在A(yíng)ctivity中:
/**
* Created by zjp on 2016/4/21 10:00.
*/
public class ViewConflickActivity extends AppCompatActivity {
@Bind(R.id.swipeRefreshLayout)
SwipeRefreshLayout swipeRefreshLayout;
@Bind(android.R.id.list)
RecyclerView recyclerView;
private LinearLayoutManager linearLayoutManager;
private int index;
private RefreshAdapter adapter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.conflick_layout);
ButterKnife.bind(this);
initViews();
}
private void inidViews() {
//設(shè)置刷新時(shí)動(dòng)畫(huà)的顏色,可以設(shè)置4個(gè)
swipeRefreshLayout.setProgressBackgroundColorSchemeResource(android.R.color.white);
swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light, android.R.color.holo_red_light, android.R.color.holo_orange_light, android.R.color.holo_green_light);
}