Я хочу реализовать пользовательский интерфейс в Jetpack Compose, где у меня есть LazyVerticalGrid. Когда я нажимаю на один элемент сетки, он должен развернуться и отобразить подробный список (изначально скрытых) подэлементов этого элемента сетки, как показано на изображении:
Расширяемая ленивая сетка
Как получить желаемый макет, чтобы эффект щелчка ограничивался выбранным элементом, а не всеми элементами его столбца?
Не удалось попытка
Я попробовал решение используя LazyColumn, но проблема в том, что метод chunked предоставляет список списков по 3 элемента в каждом. Это делает строку расширяемой, но ведет себя как двумерный массив. Мне не удалось найти j-й индекс, поэтому нажатие на один элемент приводит к одновременному расширению всех элементов в этом столбце.
сетка в исходном состоянии
Сетка, в которой развернуты все элементы одного столбца, а не один элемент
@Composable
fun ExpandableGridUsingLazyColumn() {
val items = listOf(
CollapsableSection(
title = "Electronics & Appliances",
rows = listOf("Electronics", "Laptop Accessories", "Mobile Accessories")
),
CollapsableSection(
title = "Fashion",
rows = listOf("Mens Fashion", "Women's Fashion")
),
CollapsableSection(
title = "Furniture & Home Decor",
rows = listOf("Furniture", "Home & Garden")
),
CollapsableSection(
title = "Food & Beverages",
rows = listOf("Beverages", "Dairy & Bakery", "Grocery & Staples", "Snacks & Branded Food", "Vegetables & Fruits")
),
CollapsableSection(
title = "Health & Beauty",
rows = listOf("Bath Care", "Mens Care", "Personal Care")
),
CollapsableSection(
title = "Household & Cleaning Products",
rows = listOf("Cleaning Products", "Home Essentials")
),
CollapsableSection(
title = "Vehicle Accessories",
rows = listOf()
),
CollapsableSection(
title = "Sports & Fitness",
rows = listOf()
),
CollapsableSection(
title = "Toys, Books & Hobbies",
rows = listOf("Books & Stationary", "Toys")
)
) // Example data
val columns = 3 // Number of columns
val rows = remember(items) { items.chunked(columns) }
val collapsedState = remember { rows.map { true }.toMutableStateList() }
var itemIndex = 0
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(8.dp)
) {
rows.forEachIndexed { i, rowItems ->
item {
Column {
// Header Row
Row(
modifier = Modifier
.fillMaxWidth()
,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
rowItems.forEachIndexed { index, item ->
Box(
modifier = Modifier
.weight(1f)
.aspectRatio(1f)
.background(Color.LightGray, shape = RoundedCornerShape(8.dp))
.clickable {
itemIndex = index
collapsedState[index] = !collapsedState[index]
}
,
contentAlignment = Alignment.Center
) {
Text(
text = item.title,
style = MaterialTheme.typography.bodyMedium
)
}
}
// Fill empty space if the row is not complete
repeat(columns - rowItems.size) {
Spacer(modifier = Modifier.weight(1f))
}
}
Spacer(modifier = Modifier.height(8.dp)) // Space between header rows
// Expanded Content
if (!collapsedState[itemIndex]) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
) {
rowItems[itemIndex].rows.forEach { item ->
Text(
text = "Details of Item $item",
modifier = Modifier
.padding(vertical = 4.dp)
.background(
Color(0xFFEFEFEF),
shape = RoundedCornerShape(4.dp)
)
.padding(8.dp)
)
}
}
}
}
}
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... grid-layou
Убедитесь, что щелчок по одному элементу разворачивает только этот элемент в макете LazyVerticalGrid. ⇐ Android
Форум для тех, кто программирует под Android
1737734506
Anonymous
Я хочу реализовать пользовательский интерфейс в [b]Jetpack Compose[/b], где у меня есть LazyVerticalGrid. Когда я нажимаю на один элемент сетки, он должен развернуться и отобразить подробный список (изначально скрытых) подэлементов этого элемента сетки, как показано на изображении:
Расширяемая ленивая сетка
[b]Как получить желаемый макет, чтобы эффект щелчка ограничивался выбранным элементом[/b], а не всеми элементами его столбца?
Не удалось попытка
Я попробовал решение используя LazyColumn, но проблема в том, что метод chunked предоставляет список списков по 3 элемента в каждом. Это делает строку расширяемой, но ведет себя как двумерный массив. Мне не удалось найти j-й индекс, поэтому [b]нажатие на один элемент приводит к одновременному расширению всех элементов в этом столбце[/b].
сетка в исходном состоянии
Сетка, в которой развернуты все элементы одного столбца, а не один элемент
@Composable
fun ExpandableGridUsingLazyColumn() {
val items = listOf(
CollapsableSection(
title = "Electronics & Appliances",
rows = listOf("Electronics", "Laptop Accessories", "Mobile Accessories")
),
CollapsableSection(
title = "Fashion",
rows = listOf("Mens Fashion", "Women's Fashion")
),
CollapsableSection(
title = "Furniture & Home Decor",
rows = listOf("Furniture", "Home & Garden")
),
CollapsableSection(
title = "Food & Beverages",
rows = listOf("Beverages", "Dairy & Bakery", "Grocery & Staples", "Snacks & Branded Food", "Vegetables & Fruits")
),
CollapsableSection(
title = "Health & Beauty",
rows = listOf("Bath Care", "Mens Care", "Personal Care")
),
CollapsableSection(
title = "Household & Cleaning Products",
rows = listOf("Cleaning Products", "Home Essentials")
),
CollapsableSection(
title = "Vehicle Accessories",
rows = listOf()
),
CollapsableSection(
title = "Sports & Fitness",
rows = listOf()
),
CollapsableSection(
title = "Toys, Books & Hobbies",
rows = listOf("Books & Stationary", "Toys")
)
) // Example data
val columns = 3 // Number of columns
val rows = remember(items) { items.chunked(columns) }
val collapsedState = remember { rows.map { true }.toMutableStateList() }
var itemIndex = 0
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(8.dp)
) {
rows.forEachIndexed { i, rowItems ->
item {
Column {
// Header Row
Row(
modifier = Modifier
.fillMaxWidth()
,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
rowItems.forEachIndexed { index, item ->
Box(
modifier = Modifier
.weight(1f)
.aspectRatio(1f)
.background(Color.LightGray, shape = RoundedCornerShape(8.dp))
.clickable {
itemIndex = index
collapsedState[index] = !collapsedState[index]
}
,
contentAlignment = Alignment.Center
) {
Text(
text = item.title,
style = MaterialTheme.typography.bodyMedium
)
}
}
// Fill empty space if the row is not complete
repeat(columns - rowItems.size) {
Spacer(modifier = Modifier.weight(1f))
}
}
Spacer(modifier = Modifier.height(8.dp)) // Space between header rows
// Expanded Content
if (!collapsedState[itemIndex]) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
) {
rowItems[itemIndex].rows.forEach { item ->
Text(
text = "Details of Item $item",
modifier = Modifier
.padding(vertical = 4.dp)
.background(
Color(0xFFEFEFEF),
shape = RoundedCornerShape(4.dp)
)
.padding(8.dp)
)
}
}
}
}
}
}
}
}
Подробнее здесь: [url]https://stackoverflow.com/questions/79384912/ensure-that-clicking-one-item-expands-just-this-item-in-a-lazyverticalgrid-layou[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия