怎么在Jetpack Composer中创建具有静态值可扩展列表视图

本教程将介绍如何在Jetpack Composer中创建具有静态值可扩展列表视图的处理方法,这篇教程是从别的地方看到的,然后加了一些国外程序员的疑问与解答,希望能对你有所帮助,好了,下面开始学习吧。

怎么在Jetpack Composer中创建具有静态值可扩展列表视图 教程 第1张

问题描述

我已使用静态值创建了Kotlin代码:

我想知道怎么使用Jetpack Compose创建相同的内容?我不知道

编码:

 class TestApp : AppCompatActivity() {
 
  var listAdapter: ExpandableListAdapter? = null
  var expListView: ExpandableListView? = null
  var listDataHeader: MutableList<String>? = null
  var listDataChild: HashMap<String, List<String>>? = null
 
  override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
 
expListView = findViewById<View>(R.id.lvExp) as ExpandableListView
prepareListData()
listAdapter = ExpandableListAdapter(this, listDataHeader, listDataChild)
expListView!!.setAdapter(listAdapter)
 
  }
  private fun prepareListData() {
  listDataHeader = ArrayList()
  listDataChild = HashMap()
  listDataHeader?.add(getString(R.string.q_1))
  val on_0: MutableList<String> = ArrayList()
  on_0.add(getString(R.string.faq_d_0))
  listDataChild!![listDataHeader!![0]] = on_0
}
 }

推荐答案

您可以使用LazyColumn加上可变状态列表来存储折叠状态:

@Composable
fun CollapsableLazyColumn(
 sections: List<CollapsableSection>,
 modifier: Modifier = Modifier
) {
 val collapsedState = remember(sections) { sections.map { true }.toMutableStateList() }
 LazyColumn(modifier) {
  sections.forEachIndexed { i, dataItem ->
val collapsed = collapsedState[i]
item(key = "header_$i") {
 Row(
  verticalAlignment = Alignment.CenterVertically,
  modifier = Modifier
.clickable {
 collapsedState[i] = !collapsed
}
 ) {
  Icon(
Icons.Default.run {
 if (collapsed)
  KeyboardArrowDown
 else
  KeyboardArrowUp
},
contentDescription = "",
tint = Color.LightGray,
  )
  Text(
dataItem.title,
fontWeight = FontWeight.Bold,
modifier = Modifier
 .padding(vertical = 10.dp)
 .weight(1f)
  )
 }
 Divider()
}
if (!collapsed) {
 items(dataItem.rows) { row ->
  Row {
Spacer(modifier = Modifier.size(MaterialIconDimension.dp))
Text(
 row,
 modifier = Modifier
  .padding(vertical = 10.dp)
)
  }
  Divider()
 }
}
  }
 }
}

data class CollapsableSection(val title: String, val rows: List<String>)

const val MaterialIconDimension = 24f

用法:

CollapsableLazyColumn(
 sections = listOf(
  CollapsableSection(
title = "Fruits A",
rows = listOf("Apple", "Apricots", "Avocado")
  ),
  CollapsableSection(
title = "Fruits B",
rows = listOf("Banana", "Blackberries", "Blueberries")
  ),
  CollapsableSection(
title = "Fruits C",
rows = listOf("Cherimoya", "Cantaloupe", "Cherries", "Clementine")
  ),
 ),
)

结果:

好了关于怎么在Jetpack Composer中创建具有静态值可扩展列表视图的教程就到这里就结束了,希望趣模板源码网找到的这篇技术文章能帮助到大家,更多技术教程可以在站内搜索。