安卓開發筆記 RecycleView (三)

來源:互聯網
上載者:User

標籤:idg   creat   ada   layout   list   get   weight   str   padding   

建立RecycleView的步驟:

在Layout中建立RecycleView

建立List Item 和 ViewHolder

添加RecycleView 適配器

添加LayoutManager 和 將所有事情串連起來。

 

練習一:RecycleView 布局

第一 步:在app/build.gradle(Module:app)檔案中添加依賴

dependencies {    compile fileTree(dir: ‘libs‘, include: [‘*.jar‘])    compile ‘com.android.support:appcompat-v7:25.1.0‘    // TODO (1) Add RecyclerView dependency    compile ‘com.android.support:recyclerview-v7:25.1.0‘}

 

第二步: 添加RecycleView到布局中

    <!--TODO (2) Replace the TextView with a RecyclerView with an id of "@+id/rv_numbers"-->    <!--TODO (3) Make the width and height of the RecyclerView match_parent-->    <android.support.v7.widget.RecyclerView
     android:id="@+id/rv_numbers"
android:layout_width="match_parent" android:layout_height="match_parent"> </android.support.v7.widget.RecyclerView>

 

 

練習二:使用ViewHolder

1. 在app/res/layout/目錄下建立number_list_item.xml檔案

// number_list_item.xml
<?
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="wrap_content" android:padding="16dp" > <TextView android:id="@+id/tv_item_number" android:layout_width="wrap_content" android:layout_height="wrap_content" style="@style/TextAppearance.AppCompat.Title" android:textSize="42sp" android:fontFamily="monospace" /></FrameLayout>

 

 

2. 添加 NumberViewHolder 類

class NumberViewHolder extends RecyclerView.ViewHolder {        private TextView listItemNumberView;        public NumberViewHolder(View itemView) {            super(itemView);            listItemNumberView = (TextView) itemView.findViewById(R.id.tv_item_number);            void bind(int listIndex) {                listItemNumberView.setText(String.valueOf(listIndex));            }        }    }

 

 

練習三:Adapter 適配器

適配器要求我們重寫三個函數:

onCreateViewHolder()  在RecylclerView 執行個體化一個新的ViewHolder執行個體時調用

onBindViewHolder() 在RecyclerView 想要讓使用者使用他時調用

getItemCount() 它返回資料來源中的個數

 

過程:

當RecyclerView已經初始化後,他會首先詢問Adapter將要顯示的項目個數

然後RecyclerView會要求適配器建立ViewHolder對象 在這個程序呼叫 onCreateViewHolder() 使用相應的xml來繪製

onCreateViewHolder() 函數負責建立視圖,在建立好每個viewHolder之後,RecyclerView將調用onBindViewHolder()來為每個項目填充資料

 

練習:建立Adapter

 

安卓開發筆記 RecycleView (三)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.