0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

LazyColumnとListItemでリスト画面を作成する

0
Posted at

Jetpack Composeでスクロール可能なリストを作成します。LazyColumnとListItemを使用します。

実装方法

以下はにメニュー一覧を表示する例を紹介します。LazyColumn でリスト全体を管理し、ListItem で各行のレイアウトを作成しています。
主なプロパティは以下のとおりです。

headlineContent → タイトル
supportingContent → サブタイトル
leadingContent → 左側のアイコン
trailingContent → 右側のアイコン
overlineContent → タイトル上部の補足情報などに使用します

HorizontalDivider() を追加することで、各項目の間に区切り線を表示できます。

@Composable
fun SampleListScreen() {
    val items = listOf(
        "ホーム",
        "プロフィール",
        "お知らせ",
        "設定",
        "お問い合わせ"
    )

    LazyColumn {
        items(items.size) { index ->
            ListItem(
                headlineContent = {
                    Text(items[index])
                },
                trailingContent = {
                    Icon(
                        imageVector = Icons.Default.ChevronRight,
                        contentDescription = null
                    )
                }
            )

            HorizontalDivider()
        }
    }
}

リストのクリックイベント

Modifier.clickableを使用して、リスト項目のタップ処理を実装できます。項目全体をタップ可能です。

ListItem(
    headlineContent = {
        Text(items[index])
    },
    trailingContent = {
        Icon(
            imageVector = Icons.Default.ChevronRight,
            contentDescription = null
        )
    },
    modifier = Modifier.clickable {
        Log.d("SampleList", "${items[index]}がタップされました")
        // 画面遷移処理
    }
)

外部からのデータ表示

実際は外から通信してデータを取得、表示するケースもあるので、データクラスを使用した実装方法もメモします。

data class MenuItem(
    val title: String,
    val description: String
)
@Composable
fun SampleListScreen() {
    // 外部から取得した想定のデータ
    val items = listOf(
        MenuItem("肩ロース", "柔らかい赤身"),
        MenuItem("ハラミ", "肉厚でジューシー"),
        MenuItem("ハツ", "コリコリの食感で脂や臭みは少ない 味は淡白"),
        MenuItem("タン", "弾力がありサクサクとした歯ごたえの肉質")
    )

    LazyColumn {
        items(items) { item ->
            ListItem(
                headlineContent = {
                    Text(item.title)
                },
                supportingContent = {
                    Text(item.description)
                }
            )

            HorizontalDivider()
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?