(一)前言:
RecyclerView 是Android L版本中新添加的一個用來取代ListView的SDK,它的靈活性與可替代性比listview更好。
(二)介紹:
RecyclerView與ListView原理是類似的:都是僅僅維護少量的View并且可以展示大量的數(shù)據(jù)集。RecyclerView用以下兩種方式簡化了數(shù)據(jù)的展示和處理:
- ①使用LayoutManager來確定每一個item的排列方式。
- ②為增加和刪除項目提供默認的動畫效果。
你也可以定義你自己的LayoutManager和添加刪除動畫,RecyclerView項目結(jié)構(gòu)如下:
結(jié)構(gòu)圖
Adapter:使用RecyclerView之前,你需要一個繼承自RecyclerView.Adapter的適配器,作用是將數(shù)據(jù)與每一個item的界面進行綁定。
LayoutManager:用來確定每一個item如何進行排列擺放,何時展示和隱藏。回收或重用一個View的時候,LayoutManager會向適配器請求新的數(shù)據(jù)來替換舊的數(shù)據(jù),這種機制避免了創(chuàng)建過多的View和頻繁的調(diào)用findViewById方法(與ListView原理類似)。
(三)用法:
1、如果你用的是Android Studio,必須添加依賴庫:
2、編寫代碼:
<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:你換你自己的布局就可以,主要接下來文章我打算寫SwipeRefreshLayout與Viewpager滑動沖突),主要看RecyclerView。
然后在Activity中:
/**
* 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è)置4個
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);
}