標籤: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 (三)