安卓基礎(十一)

列表-視圖

目標人羣:沒有基礎的安卓初學者
知識點:RecyclerView的使用
目標:用在頁面中使用RecyclerView展示列表數據

簡介

  • RecyclerView的佈局相關說明

正文

1.打開activity_main.xml文件,將其內部的代碼修改爲如下所示

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</RelativeLayout>
  • 此時該頁面內有一個RecyclerView控件,接下來的代碼將圍繞其進行展開

2.創建一個新的佈局文件,命名爲item_card.xml,內部的代碼爲如下所示

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <!-- 一個包涵了TextView的CardView控件 -->
    <android.support.v7.widget.CardView 
        android:id="@+id/card_view"
        android:layout_gravity="center"
        android:layout_width="200dp"
        android:layout_height="200dp"
        card_view:cardCornerRadius="4dp">

        <TextView
            android:id="@+id/info_text"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </android.support.v7.widget.CardView>
</LinearLayout>
  • 該佈局爲每個子item對應的佈局樣式

  • 此處用到了一個新的控件CardView,前往build.gradle添加新的代碼引用,如下所示

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.3'
    compile 'com.android.support:cardview-v7:21.0.+'
}

3.RecyclerView只負責UI的顯示和對數據集處理,爲了指定每個單元View的具體展示形式,我們需要爲RecyclerView指定一個 layout manager,代碼如下

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        // 當每個子View的大小在佈局中不會發生變化時,可以調用本句來提升性能
        mRecyclerView.setHasFixedSize(true);
        // 爲RecyclerView指定一個類型爲LinearLayoutManager的layout manager
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
     }
  • LinearLayoutManager爲最簡單的layout manager,即線性佈局管理

  • LinearLayoutManager有橫向和縱向兩種方向

擴展閱讀

  1. 錯開位置的網格式layout manager
  2. CardView的API說明
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章