Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

React Native 實現 ListView 分組與懸浮吸頂效果

編輯:關於 Android 程式設計

RN 裡做分組列表,思路和 Android 的 ExpandableListView 頗為相似,只是表現形式上更接近 iOS 的 UITableView:分組標題整條通欄,滾動時停在頂部。

一、特殊的數據結構

普通 ListView 吃一個數組就行,分組列表不行。RN 要求把所有內容攤平進一個大對象 dataBlob,再用兩個數組描述層次:

// 所有數據的扁平容器
var dataBlob = {
    'sectionId1'        : {...分組 1 的標題數據},
    'sectionId1:rowId1' : {...分組 1 第 1 行的數據},
    'sectionId1:rowId2' : {...分組 1 第 2 行的數據},
    'sectionId2'        : {...分組 2 的標題數據},
    'sectionId2:rowId1' : {...分組 2 第 1 行的數據},
    ...
};

// 一維數組:所有分組 id,決定分組順序
var sectionIds = ['sectionId1', 'sectionId2', 'sectionId3', ...];

// 二維數組:每個分組下的行 id
var rowIds = [
    ['rowId1', 'rowId2', ...],
    ['rowId1', 'rowId2', ...],
    ...
];

取值規則很簡單:分組標題用 sectionId 取,行數據用 sectionId:rowId 拼接取。

二、初始化 DataSource

這裡和普通 ListView 不一樣,需要同時提供分組與行的取值函數:

getInitialState() {
    var getSectionData = (dataBlob, sectionID) => {
        return dataBlob[sectionID];
    };
    var getRowData = (dataBlob, sectionID, rowID) => {
        return dataBlob[sectionID + ':' + rowID];
    };
    return {
        dataSource: new ListView.DataSource({
            getSectionData: getSectionData,
            getRowData: getRowData,
            rowHasChanged: (r1, r2) => r1 !== r2,
            sectionHeaderHasChanged: (s1, s2) => s1 !== s2
        })
    };
}

三、完整實現

import React, { Component } from 'react';
import {
    AppRegistry, StyleSheet, Text, View, ListView, TouchableOpacity, Image
} from 'react-native';

var Car = require('./Cars.json');

var SectionListView = React.createClass({

    getInitialState() {
        var getSectionData = (dataBlob, sectionID) => dataBlob[sectionID];
        var getRowData = (dataBlob, sectionID, rowID) => dataBlob[sectionID + ':' + rowID];
        return {
            dataSource: new ListView.DataSource({
                getSectionData: getSectionData,
                getRowData: getRowData,
                rowHasChanged: (r1, r2) => r1 !== r2,
                sectionHeaderHasChanged: (s1, s2) => s1 !== s2
            })
        };
    },

    componentDidMount() {
        this.loadListViewDataFormJson();
    },

    render() {
        return (
            <ListView
                contentContainerStyle={styles.listStyle}
                dataSource={this.state.dataSource}
                renderRow={this.renderRow}
                renderSectionHeader={this.renderSectionHeader}
            />
        );
    },

    /** 把原始 JSON 轉成 RN 需要的扁平結構 */
    loadListViewDataFormJson() {
        var jsonData = Car.data;
        var dataBlob = {}, sectionIDs = [], rowIDs = [];

        for (var i = 0; i < jsonData.length; i++) {
            sectionIDs.push(i);            // 1. 分組 id
            dataBlob[i] = jsonData[i].title; // 2. 分組標題數據
            rowIDs[i] = [];

            var cars = jsonData[i].cars;
            for (var j = 0; j < cars.length; j++) {
                rowIDs[i].push(j);                 // 3. 行 id
                dataBlob[i + ':' + j] = cars[j];   // 4. 行數據
            }
        }

        this.setState({
            dataSource: this.state.dataSource
                .cloneWithRowsAndSections(dataBlob, sectionIDs, rowIDs)
        });
    },

    renderRow(rowData) {
        return (
            <TouchableOpacity>
                <View style={styles.rowView}>
                    <Image source={{uri: rowData.icon}} style={styles.rowImage} />
                    <View style={styles.rowTitleSup}>
                        <Text style={styles.rowTitle}>{rowData.name}</Text>
                    </View>
                </View>
            </TouchableOpacity>
        );
    },

    renderSectionHeader(sectionData, sectionId) {
        return (
            <View style={styles.sectionView}>
                <Text style={styles.sectionTitle}>{sectionData}</Text>
            </View>
        );
    }
});

const styles = StyleSheet.create({
    listStyle: {},
    sectionView: {
        height: 22,
        backgroundColor: '#c3c3c3',
        justifyContent: 'center'
    },
    sectionTitle: {
        marginLeft: 16
    },
    rowView: {
        height: 44,
        flexDirection: 'row',
        paddingLeft: 16,
        alignItems: 'center'
    },
    rowImage: {
        width: 44,
        height: 44
    },
    rowTitleSup: {
        height: 44,
        width: 700,
        borderBottomWidth: 1,
        borderBottomColor: '#c3c3c3',
        marginLeft: 16,
        justifyContent: 'center'
    },
    rowTitle: {
        fontSize: 16
    }
});

module.exports = SectionListView;

四、Cars.json 數據結構

源數據是「分組數組」的常規嵌套形式,每個元素含一個 title 和一個 cars 數組:

{
  "data": [
    {
      "title": "A",
      "cars": [
        { "icon": "m_180_100.png", "name": "AC Schnitzer" },
        { "icon": "m_92_100.png",  "name": "阿爾法·羅密歐" },
        { "icon": "m_9_100.png",   "name": "奧迪" },
        { "icon": "m_97_100.png",  "name": "阿斯頓·馬丁" }
      ]
    },
    {
      "title": "B",
      "cars": [
        { "icon": "m_172_100.png", "name": "巴博斯" },
        { "icon": "m_157_100.png", "name": "寶駿" },
        { "icon": "m_3_100.png",   "name": "寶馬" },
        { "icon": "m_82_100.png",  "name": "保時捷" }
      ]
    }
  ]
}

後續按字母補全 C 到 Z 各分組即可,結構完全一致。


幾個實踐要點

key 的拼接方式不能改。sectionId:rowId 這個格式是約定,getRowData 裡怎麼拼,寫數據時就得怎麼拼,兩邊必須對齊。

cloneWithRowsAndSections 才是分組列表的入口。普通列表用的 cloneWithRows 在這裡無效,別混用。

rowHasChanged 與 sectionHeaderHasChanged 建議保留引用比較。默認的深比較在數據量大時開銷明顯。

懸浮效果的關鍵在 renderSectionHeader。ListView 會自動把當前所在分組的標題吸附在頂部,只要給 sectionView 一個不透明的背景色,吸頂時就不會透出下面的內容——不需要額外寫任何動畫。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved