是的,使用 Compose,您可以非常轻松地制作这样的应用程序。
这是此类 UI 的基本示例。
class MainActivity : FragmentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
AppTheme {
ItemsScreen()
}
}
}
}
class Item(val title: String, value1: Int, value2: Int, value3: Int) {
val value1 = mutableStateOf(value1)
val value2 = mutableStateOf(value2)
val value3 = mutableStateOf(value3)
val valueToSortBy: Int
get() = value1.value + value2.value + value3.value
}
class ScreenViewModel : ViewModel() {
val items = List(3) {
Item(
"Item $it",
Random.nextInt(10),
Random.nextInt(10),
Random.nextInt(10),
)
}.toMutableStateList()
fun sortItems() {
items.sortByDescending { it.valueToSortBy }
}
fun addNewItem() {
items.add(
Item(
"Item ${items.count()}",
Random.nextInt(10),
Random.nextInt(10),
Random.nextInt(10),
)
)
}
}
@Composable
fun ItemsScreen() {
val viewModel: ScreenViewModel = viewModel()
LaunchedEffect(viewModel.items.map { it.valueToSortBy }) {
viewModel.sortItems()
}
Box(
Modifier
.fillMaxSize()
.padding(10.dp)
) {
LazyColumn(
contentPadding = PaddingValues(vertical = 10.dp),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
items(viewModel.items) { item ->
ItemView(item)
}
}
FloatingActionButton(
onClick = viewModel::addNewItem,
modifier = Modifier.align(Alignment.BottomEnd)
) {
Text("+")
}
}
}
@Composable
fun ItemView(item: Item) {
Card(
elevation = 5.dp,
) {
Column(modifier = Modifier.padding(10.dp)) {
Row(
verticalAlignment = Alignment.CenterVertically,
) {
Text(
item.title,
style = MaterialTheme.typography.h5
)
Spacer(modifier = Modifier.weight(1f))
Text(
"Value to sort by: ${item.valueToSortBy}",
style = MaterialTheme.typography.body1,
fontStyle = FontStyle.Italic,
)
}
Spacer(modifier = Modifier.size(25.dp))
Row(
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier.fillMaxWidth()
) {
CounterView(value = item.value1.value, setValue = { item.value1.value = it })
CounterView(value = item.value2.value, setValue = { item.value2.value = it })
CounterView(value = item.value3.value, setValue = { item.value3.value = it })
}
}
}
}
@Composable
fun CounterView(value: Int, setValue: (Int) -> Unit) {
Row(verticalAlignment = Alignment.CenterVertically) {
CounterButton("+") {
setValue(value + 1)
}
Text(
value.toString(),
modifier = Modifier.padding(5.dp)
)
CounterButton("-") {
setValue(value - 1)
}
}
}
@Composable
fun CounterButton(text: String, onClick: () -> Unit) {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.size(45.dp)
.background(Color.LightGray)
.clickable(onClick = onClick)
) {
Text(
text,
color = Color.White,
)
}
}
我在这里按 3 个值的总和排序。请注意,像这样对项目进行排序在生产应用程序中可能没有太大的性能,您应该使用数据库来存储项目并从中请求排序的项目。