Jetpack Compose學習(9)——Compose中的列表控件(LazyRow和LazyColumn)

原文:Jetpack Compose學習(9)——Compose中的列表控件(LazyRow和LazyColumn) - Stars-One的雜貨小窩

經過前面的學習,大致上已掌握了compose的基本使用了,本篇繼續進行擴展,講解下載Compose中的列表控件LazyRowLazyColumn

之前也是講解Jetpack Compose學習(6)——關於Modifier的妙用 | Stars-One的雜貨小窩,可以通過Modifier屬性將Row和Column組件改造爲可滑動的

但是如果你需要顯示大量的項目(或一個未知長度的列表),使用像 Column 這樣的佈局會導致性能問題,因爲所有的項目都會被組合和佈局,無論它們是否可見。

本系列以往文章請查看此分類鏈接Jetpack compose學習

基本使用

這裏由於LazyRowLazyColumn用法相似,只是展示的方向不同,所以便是不各自分個章節出來了,下文以LazyColumn爲例講解

@SuppressLint("UnrememberedMutableState")
@Preview(showBackground = true)
@Composable
fun ListPageDemo() {

    //可觸發重組的List
    val list = arrayListOf<String>()

    //構造數據
    repeat(30) {
        list.add("卡片$it")
    }
    
    ComposeDemoTheme {
        Column() {
            LazyColumn {
                items(list) {
                    Text(
                        it, modifier = Modifier
                            .fillMaxWidth()
                            .height(50.dp)
                    )
                }
            }
        }
    }

}

效果如下所示:

上面主要使用了LazyListScope裏提供的items方法來構造列表

除此之外,LazyListScope也是提供了幾個不同的方法來構造列表

LazyColumn {
    // 添加單個項目
    item {
        Text(text = "First item")
    }

    // 添加五個項目
    items(5) { index ->
        Text(text = "Item: $index")
    }

    // 添加其他單個項目
    item {
        Text(text = "Last item")
    }
    
}

可觀察數據列表 mutableStateListOf()

上面那種,由於我們是使用的基本數據類型的ArrayList,所以在列表數據發生變更時,不會觸發重組

如果我們想要實現可觸發重組的數據列表,可以使用Compose中提供的mutableStateListOf()方法來創建數據列表

如下面例子:

@SuppressLint("UnrememberedMutableState")
@Preview(showBackground = true)
@Composable
fun ListPageDemo() {

    //可觸發重組的List
    val list = mutableStateListOf<String>()

    repeat(30) {
        list.add("卡片$it")
    }
    ComposeDemoTheme {
        Box(modifier = Modifier) {
            Column() {
                LazyColumn {
                    items(list) {
                        Text(
                            it, modifier = Modifier
                                .fillMaxWidth()
                                .height(50.dp)
                        )
                    }
                }
            }
            //設置靠右下角
            Column(
                horizontalAlignment = Alignment.End,
                verticalArrangement = Arrangement.Bottom,
                modifier = Modifier.fillMaxSize().padding(end = 16.dp,bottom = 16.dp)
            ) {
                FloatingActionButton(onClick = {
                    //移除列表最後一個數據
                    list.removeLast()
                }) {
                    Icon(
                        imageVector = Icons.Default.Clear,
                        contentDescription = null
                    )
                }
                FloatingActionButton(onClick = {
                    //添加一個新的數據
                    val time = System.currentTimeMillis()
                    list.add(time.toString())
                }) {
                    Icon(
                        imageVector = Icons.Default.Add,
                        contentDescription = null
                    )
                }
            }
        }

    }
}

爲了方便演示,加了兩個懸浮按鈕,用來測試數據的增加和刪除,效果如下所示:

mutableStateListOf()方法返回的類型是SnapshotStateList,此類型和ArrayList一樣,有着相關的添加,移除數據等方法,同時還能觸發Compose中的重組操作

屬性

我們從構造方法來看下LazyColumn具有什麼參數可以設置

fun LazyColumn(
    modifier: Modifier = Modifier,
    state: LazyListState = rememberLazyListState(),
    contentPadding: PaddingValues = PaddingValues(0.dp),
    reverseLayout: Boolean = false,
    verticalArrangement: Arrangement.Vertical =
        if (!reverseLayout) Arrangement.Top else Arrangement.Bottom,
    horizontalAlignment: Alignment.Horizontal = Alignment.Start,
    flingBehavior: FlingBehavior = ScrollableDefaults.flingBehavior(),
    content: LazyListScope.() -> Unit
){}

modifier想必也不用多說了,不清楚了可以看下前面的文章

FlingBehavior這個屬性是用於定義滑動動作釋放後的速度變化邏輯的,比如,當滑動動作釋放後,列表還將繼續滑動,速度依時遞減

此屬性有點不太常用,就不講解了

由於state這個屬性涉及東西較多,所以單獨放在後面講解

contentPadding

此屬性主要是用來設置內邊距的,取值爲PaddingValues

PaddingValues方法的參數有三種,根據需要選擇即可:

  • PaddingValues(all:Dp)
  • PaddingValues(horizontal: Dp, vertical: Dp)
  • PaddingValues(start: Dp = 0.dp,top: Dp = 0.dp,end: Dp = 0.dp,bottom: Dp = 0.dp)

示例代碼(設置內邊距爲16dp):

LazyColumn(contentPadding = PaddingValues(16.dp)) {
    items(list) {
        Text(
            it, modifier = Modifier
                .fillMaxWidth()
                .height(50.dp)
        )
    }
}

效果:

reverseLayout

將列表順序反轉過來,接收一個boolean數值

示例代碼:

LazyColumn(reverseLayout = true) {
    items(list) {
        Text(
            it, modifier = Modifier
                .fillMaxWidth()
                .height(50.dp)
        )
    }
}

效果:

PS:這個時候如果新增一個數據項item,item會出現在最上面的位置

verticalArrangement

此屬性組主要是用來設置item的相互間距,針對的是LazyColumn

PS: LazyRow則是horizontalArrangement屬性

LazyColumn(verticalArrangement = Arrangement.spacedBy(10.dp)) {
    items(list) {
        Text(
            it, modifier = Modifier
                .fillMaxWidth()
                .height(50.dp)
                .background(color = Color.Yellow)
        )
    }
}

效果:

horizontalAlignment

設置水平對齊方式,是針對LazyColumn

PS:LazyRow中的屬性則是verticalAlignment

LazyColumn(Modifier.fillMaxWidth(),horizontalAlignment = Alignment.End) {
    items(list) {
        Text(
            it, modifier = Modifier
                .height(50.dp)
                .background(color = Color.Yellow)
        )
    }
}

注意,要設置LazyColumn爲填充最大寬度,然後item項是沒有最大寬度的,纔會看到效果

效果:

state

接收LazyListState對象,主要是提供一個可觀察的狀態,用來實現控制和觀察列表組件,如滾動到列表某一項的時候,需要展示一個懸浮按鈕等邏輯

LazyListState有以下常用屬性:

  • firstVisibleItemIndex 當前頁面列表顯示的第一項的下標
  • firstVisibleItemScrollOffset 當前頁面列表顯示的第一項的滑動偏移量
  • interactionSource 當列表被拖拽時候,會觸發對應的分發事件,interactionSource存放着相關的事件state
  • layoutInfo 列表佈局相關信息
  • isScrollInProgress 一個boolean數值,標識當前列表是否處於滑動狀態

對滾動位置做出反應示例

我們以firstVisibleItemIndex爲例,可以實現滾動到列表某一項的時候,需要展示一個懸浮按鈕的功能

要實現上述功能,肯定得要一個boolean的state對象纔行,但firstVisibleItemIndex只是一個Int類型,如何將其轉換爲可觀察的boolean數值(MutableState<Boolean>)呢?

這裏可以使用derivedStateOf()方法來進行轉換

val state = rememberLazyListState()
val showButton by remember {
    derivedStateOf {
        state.firstVisibleItemIndex > 5
    }
}

示例代碼:

@SuppressLint("UnrememberedMutableState")
@Preview(showBackground = true)
@Composable
fun ListPageDemo() {

    //可觸發重組的List
    val list = mutableStateListOf<String>()

    repeat(30) {
        list.add("卡片$it")
    }
    val state = rememberLazyListState()


    val showButton by remember {
        derivedStateOf {
            state.firstVisibleItemIndex > 5
        }
    }
   
    ComposeDemoTheme {
        Box(modifier = Modifier) {
            Column() {
                LazyColumn(state = state,modifier = Modifier.fillMaxWidth()) {
                    items(list) {
                        Text(
                            it, modifier = Modifier
                                .height(50.dp)
                                .background(color = Color.Yellow)
                        )
                    }
                }
            }

            if (showButton) {
                //這裏由於要設置懸浮按鈕的位置,所以外層需要一個Box佈局
                Box(Modifier.fillMaxSize().padding(bottom = 16.dp),contentAlignment = Alignment.BottomCenter) {
                    FloatingActionButton(onClick = {
                    }) {
                        Icon(
                            imageVector = Icons.Default.KeyboardArrowUp,
                            contentDescription = null
                        )
                    }
                }
            }
            //設置靠右下角
            Column(
                horizontalAlignment = Alignment.End,
                verticalArrangement = Arrangement.Bottom,
                modifier = Modifier
                    .fillMaxSize()
                    .padding(end = 16.dp, bottom = 16.dp)
            ) {
                FloatingActionButton(onClick = {
                    //移除列表最後一個數據
                    list.removeLast()
                }) {
                    Icon(
                        imageVector = Icons.Default.Clear,
                        contentDescription = null
                    )
                }
                FloatingActionButton(onClick = {
                    //添加一個新的數據
                    val time = System.currentTimeMillis()
                    list.add(time.toString())
                }) {
                    Icon(
                        imageVector = Icons.Default.Add,
                        contentDescription = null
                    )
                }
            }
        }

    }
}

可以從下圖看到,當列表的第一項爲卡片6的時候,按鈕即顯示出來了:

控制滾動

除此之外,LazyListState還提供了一些方法,可以讓我們控制列表自動滾動

  • scrollToItem(index:Int,scrollOffset: Int = 0) 滾動到指定的數據項
  • animateScrollToItem(index:Int,scrollOffset: Int = 0) 平滑滾動到指定的數據項

注意這兩個方法都是掛起方法,需要在協程中使用

我們基於上面的例子,加以改造下,實現點擊懸浮按鈕,列表滾動回頂部的功能

爲例方便閱讀,下面的代碼稍微省略了一些不重要的代碼:

@SuppressLint("UnrememberedMutableState")
@Preview(showBackground = true)
@Composable
fun ListPageDemo() {

    ...
    
    // 記住一個協程作用域,以便能夠啓動滾動操作
    val coroutineScope = rememberCoroutineScope()
   
    FloatingActionButton(onClick = {
        coroutineScope.launch {
            //滾動到第一項
            state.animateScrollToItem(0)
        }
    }) {
        Icon(
            imageVector = Icons.Default.KeyboardArrowUp,
            contentDescription = null
        )
    }
}

這裏需要注意的是,使用滾動得通過協程來進行調用,通過rememberCoroutineScope()來得到一個協程作用域對象

效果如下圖所示:

高級使用

1.粘性標題

LazyListScope除了items等方法,還有stickyHeader方法,幫助我們快速實現粘性標題的效果,如下圖所示:

代碼:

//可觸發重組的List
val list = mutableStateListOf<String>()

repeat(30) {
    list.add("title1 卡片$it")
}

//可觸發重組的List
val list1 = mutableStateListOf<String>()

repeat(30) {
    list1.add("title2 卡片$it")
}
    
LazyColumn(state = state, modifier = Modifier.fillMaxWidth()) {

    stickyHeader {
        Text(
            "title1",
            modifier = Modifier
                .fillMaxWidth()
                .background(color = Color.Green)
        )
    }
    items(list){
        Text(
            it, modifier = Modifier
                .height(50.dp)
                .background(color = Color.Yellow)
        )
    }
    stickyHeader {
        Text(
            "title2",
            modifier = Modifier
                .fillMaxWidth()
                .background(color = Color.Green)
        )
    }
    items(list1){
        Text(
            it, modifier = Modifier
                .height(50.dp)
                .background(color = Color.Yellow)
        )
    }

}

上面與之前的代碼,多了一個數據源list1來,當然還可以把代碼通過循環來精簡一下,這裏不再過多補充了

2.item動畫

  • animateItemPlacement 但item重新排序的動畫

截止到目前,item動畫目前只有重新排序的動畫,其他的添加和移除item的動畫官方還在開發中,詳情可看問題 150812265

測試的時候發現沒有此API,似乎也是1.2.0以後的版本纔有的API,而且是在實驗中

示例代碼:

LazyColumn {
    items(books, key = { it.id }) {
        Row(Modifier.animateItemPlacement()) {
            // ...
        }
    }
}

自定義動畫:

LazyColumn {
    items(books, key = { it.id }) {
        Row(Modifier.animateItemPlacement(
            tween(durationMillis = 250)
        )) {
            // ...
        }
    }
}

PS: 關於自定義動畫,後面我會再出新的章節講解,目前代碼就先貼着

3.分頁

藉助 Paging 庫,應用可以支持包含大量列表項的列表,根據需要加載和顯示小塊的列表。Paging 3.0 及更高版本通過 androidx.paging:paging-compose 庫提供 Compose 支持。

注意:只有 Paging 3.0 及更高版本提供 Compose 支持。如果您使用的是較低版本的 Paging 庫,則需先遷移到 3.0。

如需顯示分頁內容列表,可以使用 collectAsLazyPagingItems() 擴展函數,然後將返回的 LazyPagingItems 傳入 LazyColumn 中的 items()。

與視圖中的 Paging 支持類似,您可以通過檢查 item 是否爲 null,在加載數據時顯示佔位符

import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.items

@Composable
fun MessageList(pager: Pager<Int, Message>) {
    val lazyPagingItems = pager.flow.collectAsLazyPagingItems()

    LazyColumn {
        items(
          items = lazyPagingItems,
          // The key is important so the Lazy list can remember your
          // scroll position when more items are fetched!
          key = { message -> message.id }
        ) { message ->
            if (message != null) {
                MessageRow(message)
            } else {
                MessagePlaceholder()
            }
        }
    }
}

暫時貼上些代碼,後面可能與網絡請求一起講解,敬請期待...

更優雅使用列表組件

1.item綁定key

在上文開始也提到,我們是使用LazyListScope裏的items方法來構建數據項的,但是我們並沒有爲我們的每一項數據設置一個key,所以會導致以下問題:

如果數據集發生變化,這可能會導致問題,因爲改變位置的 item 會失去任何記憶中的狀態。
如果你想象一下 LazyRow 在LazyColumn 中的情景,如果該行改變了 item 的位置,用戶就會失去他們在該行中的滾動位置。

所以這個時候,我們可以通過items方法裏的keys參數來進行設置

此參數接收一個lambda表達式(item: T) -> Any

這裏的Any是這裏可返回任何類型的數據,但必須要要所提供的數據必須能夠被存儲在一個Bundle中,具體可點擊鏈接查看該類文檔

LazyColumn(state = state, modifier = Modifier.fillMaxWidth()) {
    items(list, key = {
        //這裏可返回任何類型的數據(Any),但必須要要所提供的數據必須能夠被存儲在一個 Bundle 中
        //直接使用本身作爲字符串
        it
    }) {
        Text(
            it, modifier = Modifier
                .height(50.dp)
                .background(color = Color.Yellow)
        )
    }
}

2.使用contentType更好複用組件

如果需要複用數據項內容時,可使用contentType來標明類型,如下的示例代碼

PS:此API在1.2.0版本提供,截止發文日期,1.2.0還處於beta中,可以查閱Jetpack各庫版本

LazyColumn {
    items(elements, contentType = { it.type }) {
        // ...
    }
}

3.item的注意項

  • item最好定義固定寬高

例如,當您希望在後期階段異步檢索一些數據(例如圖片)以填充列表項時。

這會使延遲佈局在首次衡量時組合其所有項,因爲項的高度爲 0 像素,所以這類項可完全適合視口大小。

待這些項加載完畢且高度增加後,延遲佈局隨後會捨棄首次不必要組合起來的所有其他項,因爲這些項實際上無法適合視口。

@Composable
fun Item() {
    Image(
        painter = rememberImagePainter(data = imageUrl),
        modifier = Modifier.size(30.dp),
        // ...
    )
}
  • 建議多個元素放入一個項中
LazyColumn(
    // ...
) {
    item { Item(0) }
    item {
        Item(1)
        Divider()
    }
    item { Item(2) }
    // ...
}
  • 避免嵌套可向同一方向滾動的組件

如以下不推薦的代碼:

// Throws IllegalStateException
Column(
    modifier = Modifier.verticalScroll(state)
) {
    LazyColumn {
        // ...
    }
}

參考

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章