JetpackCompose 之 状态学习

2024-01-28 22:44

本文主要是介绍JetpackCompose 之 状态学习,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.无状态组件

1.1导入依赖

    implementation("androidx.core:core-ktx:1.9.0")implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.6.1")implementation("androidx.activity:activity-compose:1.7.0")implementation(platform("androidx.compose:compose-bom:2023.03.00"))implementation("androidx.compose.ui:ui")implementation("androidx.compose.ui:ui-graphics")implementation("androidx.compose.ui:ui-tooling-preview")implementation("androidx.compose.material3:material3")implementation("com.google.android.material:material:1.11.0")implementation("androidx.compose.material:material-icons-extended:1.5.4")implementation("androidx.compose.runtime:runtime-livedata:1.5.4")implementation("androidx.compose.runtime:runtime:1.5.4")testImplementation("junit:junit:4.13.2")androidTestImplementation("androidx.test.ext:junit:1.1.5")androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")androidTestImplementation(platform("androidx.compose:compose-bom:2023.03.00"))androidTestImplementation("androidx.compose.ui:ui-test-junit4")debugImplementation("androidx.compose.ui:ui-tooling")debugImplementation("androidx.compose.ui:ui-test-manifest")

strings.xml

<resources><string name="app_name">JetpackComposeState</string><string name="cd_expand">Expand</string><string name="cd_collapse">Collapse</string><string name="cd_crop_square">Crop</string><string name="cd_done">Done</string><string name="cd_event">Event</string><string name="cd_privacy">Privacy</string><string name="cd_restore">Restore</string>d
</resources>

themes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources><style name="Theme.JetpackComposeState" parent="android:Theme.Material.Light.NoActionBar" /><style name="Theme.JetpackComposeState.NoActionBar"><item name="android:windowActionBar">false</item><item name="android:windowNoTitle">true</item></style>
</resources>

1.2 数据类

package com.tiger.jetpackcomposestate.todoimport androidx.annotation.StringRes
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CropSquare
import androidx.compose.material.icons.filled.Done
import androidx.compose.material.icons.filled.Event
import androidx.compose.material.icons.filled.PrivacyTip
import androidx.compose.material.icons.filled.RestoreFromTrash
import androidx.compose.material.icons.filled.Square
import androidx.compose.ui.graphics.vector.ImageVector
import com.tiger.jetpackcomposestate.R
import java.util.UUIDdata class TodoItem(val task:String,val icon:TodoIcon = TodoIcon.Default,val id:UUID=UUID.randomUUID())enum class TodoIcon(val imageVector: ImageVector,@StringRes val contentDescription: Int
){//使用了 Material Design 的图标Square(Icons.Default.CropSquare, R.string.cd_expand),Done(Icons.Default.Done, R.string.cd_done),Event(Icons.Default.Event, R.string.cd_event),Privacy(Icons.Default.PrivacyTip, R.string.cd_privacy),Trash(Icons.Default.RestoreFromTrash, R.string.cd_restore);companion object {val Default = Square}}
package com.tiger.jetpackcomposestate.todo.oneimport androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.tiger.jetpackcomposestate.todo.TodoItem@Composable
fun TodoScreen(items:List<TodoItem>
){Column() {LazyColumn(modifier = Modifier.weight(1f),//优先修饰 列表的布局contentPadding = PaddingValues(top = 8.dp)){items(items){TodoRow(todo = it, modifier = Modifier.fillParentMaxWidth())}}Button(onClick = {},modifier = Modifier.padding(16.dp).fillMaxWidth()) {Text(text = "Add random item" )}}}@Composable
fun TodoRow(todo: TodoItem,modifier: Modifier = Modifier
){Row(modifier = modifier.padding(horizontal = 16.dp, vertical = 8.dp),horizontalArrangement = Arrangement.SpaceBetween  //子元素水平均匀分布) {Text(text = todo.task)Icon(imageVector = todo.icon.imageVector,contentDescription = stringResource(id = todo.icon.contentDescription))//stringResource去到strings.xml文件里去找到对应的字符串 描述}}
package com.tiger.jetpackcomposestate.todo.oneimport android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.runtime.Composable
import com.tiger.jetpackcomposestate.todo.TodoIcon
import com.tiger.jetpackcomposestate.todo.TodoItem
import com.tiger.jetpackcomposestate.ui.theme.JetpackComposeStateThemeclass TodoActivity : ComponentActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContent {JetpackComposeStateTheme {TodoActivityScreen()}}}@Composableprivate fun TodoActivityScreen() {val items = listOf(TodoItem(task = "Learn compose", icon = TodoIcon.Event),TodoItem(task = "Take the codelab"),TodoItem(task = "Apply state", icon = TodoIcon.Done),TodoItem(task = "Build dynamic UIs", icon = TodoIcon.Square),)TodoScreen(items)}
}

 

TodoViewModel.kt

package com.jmj.jetpackcomposestate.todo.oneimport androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.jmj.jetpackcomposestate.todo.TodoItemclass TodoViewModel:ViewModel(){private var _todoItems = MutableLiveData(listOf<TodoItem>())  //这是一个状态val  todoItems:LiveData<List<TodoItem>> = _todoItemsfun addItem(item:TodoItem){//添加_todoItems.value = _todoItems.value!! + listOf(item)}fun removeItem(item:TodoItem){//删除_todoItems.value =_todoItems.value!!.toMutableList().also {it.remove(item)}}
}

 TodoScreen.kt

package com.jmj.jetpackcomposestate.todo.oneimport androidx.compose.foundation.clickable
import com.jmj.jetpackcomposestate.todo.TodoItemimport androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.jmj.jetpackcomposestate.util.generateRandomTodoItem@Composable
fun TodoScreen(items:List<TodoItem>,onAddItem: (TodoItem) ->Unit,onRemoveItem: (TodoItem) ->Unit
){Column() {LazyColumn(modifier = Modifier.weight(1f),//优先修饰 列表的布局contentPadding = PaddingValues(top = 8.dp)){items(items){TodoRow(todo = it, modifier = Modifier.fillParentMaxWidth(), onItemClicked = {onRemoveItem(it)})}}Button(onClick = {onAddItem(generateRandomTodoItem())},modifier = Modifier.padding(16.dp).fillMaxWidth()) {Text(text = "Add random item" )}}}@Composable
fun TodoRow(todo: TodoItem,onItemClicked:(TodoItem) -> Unit,modifier: Modifier = Modifier,){Row(modifier = modifier.clickable{onItemClicked(todo)}.padding(horizontal = 16.dp, vertical = 8.dp),horizontalArrangement = Arrangement.SpaceBetween  //子元素水平均匀分布) {Text(text = todo.task)Icon(imageVector = todo.icon.imageVector,contentDescription = stringResource(id = todo.icon.contentDescription))//stringResource去到strings.xml文件里去找到对应的字符串 描述}}

TodoAcitivity.kt

package com.jmj.jetpackcomposestate.todo.oneimport android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import com.jmj.jetpackcomposestate.todo.TodoIcon
import com.jmj.jetpackcomposestate.todo.TodoItem
import com.jmj.jetpackcomposestate.ui.theme.JetpackComposeStateThemeclass TodoActivity : ComponentActivity() {private val todoViewModel by viewModels<TodoViewModel>()override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContent {JetpackComposeStateTheme {TodoActivityScreen()}}}@Composableprivate fun TodoActivityScreen() {
//        val items = listOf(
//            TodoItem(task = "Learn compose", icon = TodoIcon.Event),
//            TodoItem(task = "Take the codelab"),
//            TodoItem(task = "Apply state", icon = TodoIcon.Done),
//            TodoItem(task = "Build dynamic UIs", icon = TodoIcon.Square),
//        )
//
//        TodoScreen(items)val items:List<TodoItem> by todoViewModel.todoItems.observeAsState(initial = listOf())TodoScreen(items=items,onAddItem = {  todoViewModel.addItem(it) },onRemoveItem = {todoViewModel.removeItem(it)})}
}

2.重组

 

package com.jmj.jetpackcomposestate.todo.oneimport androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.tiger.jetpackcomposestate.todo.TodoItem
import com.tiger.jetpackcomposestate.util.generateRandomTodoItem
import kotlin.random.Random@Composable
fun TodoScreen(items: List<TodoItem>,onAddItem: (TodoItem) -> Unit,onRemoveItem: (TodoItem) -> Unit
) {Column() {LazyColumn(modifier = Modifier.weight(1f),//优先修饰 列表的布局 表示剩下多少空间就站多少空间contentPadding = PaddingValues(top = 8.dp)) {items(items) {TodoRow(todo = it,modifier = Modifier.fillParentMaxWidth(),onItemClicked = onRemoveItem)}//            item {
//                Button(
//                    onClick = {
//                        onAddItem(generateRandomTodoItem())
//                    },
//                    modifier = Modifier
//                        .padding(16.dp)
//                        .fillMaxWidth()
//
//                ) {
//                    Text(text = "Add random item")
//
//                }
//            }}Button(onClick = {onAddItem(generateRandomTodoItem())},modifier = Modifier.padding(16.dp).fillMaxWidth(),shape = RoundedCornerShape(0.dp)) {Text(text = "Add random item")}}
}@Composable
fun TodoRow(todo: TodoItem,onItemClicked: (TodoItem) -> Unit,modifier: Modifier = Modifier,) {Row(modifier = modifier.clickable {onItemClicked(todo)}.padding(horizontal = 16.dp, vertical = 8.dp),horizontalArrangement = Arrangement.SpaceBetween  //子元素水平均匀分布) {Text(text = todo.task)val iconAlpha: Float = remember(todo.id) {randomTint()}Icon(imageVector = todo.icon.imageVector,tint = LocalContentColor.current.copy(alpha = iconAlpha) //用来隐式传参, contentDescription = stringResource(id = todo.icon.contentDescription))//stringResource去到strings.xml文件里去找到对应的字符串 描述}
}private fun randomTint(): Float {return Random.nextFloat().coerceIn(0.3f, 0.9f)
}

 

 3.MutableState

package com.jmj.jetpackcomposestate.todo.oneimport androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import com.jmj.jetpackcomposestate.todo.TodoItem//输入框
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TodoInputText(text: String,onTextChange: (String) -> Unit,modifier: Modifier = Modifier
) {//输入框TextField(value = text,onValueChange = onTextChange,colors = TextFieldDefaults.textFieldColors(containerColor = Color.Transparent),maxLines = 1,modifier = modifier)}//按钮
@Composable
fun TodoEditText(onClick: () -> Unit,text: String,modifier: Modifier = Modifier,enabled: Boolean = true
) {TextButton(onClick = onClick,shape = CircleShape,colors = ButtonDefaults.buttonColors(),modifier = modifier,enabled = enabled) {Text(text = text)}}@Composable
fun TodoItemInput(onItemComplete: (TodoItem) -> Unit
) {//    val (text, setText) = rememberSaveable { mutableStateOf("") } //屏幕旋转之后会保存值/*** 这个函数使用remember 给自己添加内存 ,然后在内存 中存储 一个由  mutableStateOf 创建的 MutableState<String>*  它是Compose 的内置类型 ,提供了一个可观察的状态持有者*  val (text, setText) = remember{ mutableStateOf(default) }*  对 value 的任何更改都将 自动重新 组合读取此状态的任何可组合函数*/val (text, setText) = remember{ mutableStateOf("") } //屏幕旋转之后不会会保存值Column {Row(Modifier.padding(horizontal = 16.dp).padding(top = 16.dp)) {//输入框TodoInputText(text = text,onTextChange = setText,//setText相当于onTextChange{ text=it }他这里用了语法糖modifier = Modifier.weight(1f).padding(end = 8.dp))//按钮TodoEditText(onClick = {onItemComplete(TodoItem(text))setText("")},text = "Add",modifier = Modifier.align(Alignment.CenterVertically),enabled = text.isNotBlank())}}}

 做出下面的选择按钮

package com.jmj.jetpackcomposestate.todo.oneimport androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.FastOutLinearInEasing
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.TweenSpec
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButtonColors
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.jmj.jetpackcomposestate.todo.TodoIcon
import com.jmj.jetpackcomposestate.todo.TodoItem//输入框
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TodoInputText(text: String,onTextChange: (String) -> Unit,modifier: Modifier = Modifier
) {//输入框TextField(value = text,onValueChange = onTextChange,colors = TextFieldDefaults.textFieldColors(containerColor = Color.Transparent),maxLines = 1,modifier = modifier)}//按钮
@Composable
fun TodoEditText(onClick: () -> Unit,text: String,modifier: Modifier = Modifier,enabled: Boolean = true
) {TextButton(onClick = onClick,shape = CircleShape,colors = ButtonDefaults.buttonColors(),modifier = modifier,enabled = enabled) {Text(text = text)}}//一排图标 ,根据文本框是否有内容,自动收起和弹出,带动画效果
@Composable
fun AnimatedIconRow(icon: TodoIcon,onIconChange: (TodoIcon) -> Unit,modifier: Modifier = Modifier,visible: Boolean = true //可见性 状态  根据我们输入是否有内容来判度是否显示
) {val enter = remember {fadeIn(animationSpec = TweenSpec(300, easing = FastOutLinearInEasing)) //300ms打开 ,预定效果器}//淡入动画val exit = remember {fadeOut(animationSpec = TweenSpec(100, easing = FastOutSlowInEasing))}//淡出动画Box(modifier = modifier.defaultMinSize(minHeight = 16.dp)) {//默认最小高度16dpAnimatedVisibility(visible = visible,enter = enter,//进入exit = exit //退出) {//动画效果IconRow(icon = icon, onIconChange = onIconChange)}}}@Composable
fun IconRow(icon: TodoIcon,onIconChange: (TodoIcon) -> Unit,modifier: Modifier = Modifier
) {LazyRow(modifier = modifier) {val itemsIcon = TodoIcon.values() + TodoIcon.values()items(items = itemsIcon) {SelectableIconButton(icon = it.imageVector,iconContentDescription = it.contentDescription,onIconSelected = { onIconChange(it) },isSelected = (it == icon))}
//        for (todoIcon in TodoIcon.values()) {
//            SelectableIconButton(
//                icon = todoIcon.imageVector,
//                iconContentDescription = todoIcon.contentDescription,
//                onIconSelected = { onIconChange(todoIcon) },
//                isSelected = (todoIcon == icon)
//
//            )
//        }}}@Composable
fun SelectableIconButton(icon: ImageVector,iconContentDescription: Int,onIconSelected: () -> Unit,isSelected: Boolean,modifier: Modifier = Modifier
) {//图标选中和未选中状态,颜色是不一样的val tint = if (isSelected) {//选择之后的颜色MaterialTheme.colorScheme.primary   //蓝色} else {MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f) //黑色}TextButton(onClick = { onIconSelected() },shape = CircleShape,modifier = modifier) {Column {Icon(imageVector = icon,tint = tint,contentDescription = stringResource(id = iconContentDescription))if (isSelected) {//如果被选中了  下划线Box(modifier = Modifier.padding(top = 3.dp).width(icon.defaultWidth).height(1.dp).background(tint))} else {Spacer(modifier = Modifier.height(4.dp))}}}}@Composable
fun TodoItemInput(onItemComplete: (TodoItem) -> Unit
) {//    val (text, setText) = rememberSaveable { mutableStateOf("") } //屏幕旋转之后会保存值/*** 这个函数使用remember 给自己添加内存 ,然后在内存 中存储 一个由  mutableStateOf 创建的 MutableState<String>*  它是Compose 的内置类型 ,提供了一个可观察的状态持有者*  val (text, setText) = remember{ mutableStateOf(default) }*  对 value 的任何更改都将 自动重新 组合读取此状态的任何可组合函数*/val (text, setText) = remember { mutableStateOf("") } //屏幕旋转之后不会会保存值val (icon, setIcon) = remember { mutableStateOf(TodoIcon.Default) }val iconsVisible = text.isNotBlank()if (text.isBlank()) {setIcon(TodoIcon.Default)}Column {Row(Modifier.padding(horizontal = 16.dp).padding(top = 16.dp)) {//输入框TodoInputText(text = text,onTextChange = setText,//setText相当于onTextChange{ text=it }他这里用了语法糖modifier = Modifier.weight(1f).padding(end = 8.dp))//按钮TodoEditText(onClick = {onItemComplete(TodoItem(text, icon))setText("")},text = "Add",modifier = Modifier.align(Alignment.CenterVertically),enabled = text.isNotBlank())}AnimatedIconRow(icon = icon, {setIcon(it)}, Modifier.padding(top = 10.dp),iconsVisible)Text(text = "测试")}}

4. 软键盘

package com.jmj.jetpackcomposestate.todo.twoimport androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.FastOutLinearInEasing
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.TweenSpec
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButtonColors
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import com.jmj.jetpackcomposestate.todo.TodoIcon
import com.jmj.jetpackcomposestate.todo.TodoItem//输入框
@OptIn(ExperimentalMaterial3Api::class, ExperimentalComposeUiApi::class)
@Composable
fun TodoInputText(text: String,onTextChange: (String) -> Unit,modifier: Modifier = Modifier,onImeAction: () -> Unit ={ }
) {val keyboardController = LocalSoftwareKeyboardController.current//输入框TextField(value = text,onValueChange = onTextChange,colors = TextFieldDefaults.textFieldColors(containerColor = Color.Transparent),maxLines = 1,modifier = modifier,//配置软件盘keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done),keyboardActions = KeyboardActions(onDone = {//点击完成之后的回调函数onImeAction()//隐藏软键盘keyboardController?.hide()}))}//按钮
@Composable
fun TodoEditText(onClick: () -> Unit,text: String,modifier: Modifier = Modifier,enabled: Boolean = true
) {TextButton(onClick = onClick,shape = CircleShape,colors = ButtonDefaults.buttonColors(),modifier = modifier,enabled = enabled) {Text(text = text)}}//一排图标 ,根据文本框是否有内容,自动收起和弹出,带动画效果
@Composable
fun AnimatedIconRow(icon: TodoIcon,onIconChange: (TodoIcon) -> Unit,modifier: Modifier = Modifier,visible: Boolean = true //可见性 状态  根据我们输入是否有内容来判度是否显示
) {val enter = remember {fadeIn(animationSpec = TweenSpec(300, easing = FastOutLinearInEasing)) //300ms打开 ,预定效果器}//淡入动画val exit = remember {fadeOut(animationSpec = TweenSpec(100, easing = FastOutSlowInEasing))}//淡出动画Box(modifier = modifier.defaultMinSize(minHeight = 16.dp)) {//默认最小高度16dpAnimatedVisibility(visible = visible,enter = enter,//进入exit = exit //退出) {//动画效果IconRow(icon = icon, onIconChange = onIconChange)}}}@Composable
fun IconRow(icon: TodoIcon,onIconChange: (TodoIcon) -> Unit,modifier: Modifier = Modifier
) {LazyRow(modifier = modifier) {val itemsIcon = TodoIcon.values() + TodoIcon.values()items(items = itemsIcon) {SelectableIconButton(icon = it.imageVector,iconContentDescription = it.contentDescription,onIconSelected = { onIconChange(it) },isSelected = (it == icon))}
//        for (todoIcon in TodoIcon.values()) {
//            SelectableIconButton(
//                icon = todoIcon.imageVector,
//                iconContentDescription = todoIcon.contentDescription,
//                onIconSelected = { onIconChange(todoIcon) },
//                isSelected = (todoIcon == icon)
//
//            )
//        }}}@Composable
fun SelectableIconButton(icon: ImageVector,iconContentDescription: Int,onIconSelected: () -> Unit,isSelected: Boolean,modifier: Modifier = Modifier
) {//图标选中和未选中状态,颜色是不一样的val tint = if (isSelected) {//选择之后的颜色MaterialTheme.colorScheme.primary   //蓝色} else {MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f) //黑色}TextButton(onClick = { onIconSelected() },shape = CircleShape,modifier = modifier) {Column {Icon(imageVector = icon,tint = tint,contentDescription = stringResource(id = iconContentDescription))if (isSelected) {//如果被选中了  下划线Box(modifier = Modifier.padding(top = 3.dp).width(icon.defaultWidth).height(1.dp).background(tint))} else {Spacer(modifier = Modifier.height(4.dp))}}}}@Composable
fun TodoItemInput(onItemComplete: (TodoItem) -> Unit
) {//    val (text, setText) = rememberSaveable { mutableStateOf("") } //屏幕旋转之后会保存值/*** 这个函数使用remember 给自己添加内存 ,然后在内存 中存储 一个由  mutableStateOf 创建的 MutableState<String>*  它是Compose 的内置类型 ,提供了一个可观察的状态持有者*  val (text, setText) = remember{ mutableStateOf(default) }*  对 value 的任何更改都将 自动重新 组合读取此状态的任何可组合函数*/val (text, setText) = remember { mutableStateOf("") } //屏幕旋转之后不会会保存值val (icon, setIcon) = remember { mutableStateOf(TodoIcon.Default) }val iconsVisible = text.isNotBlank()//点击 "add" 按钮,提交要做的事情val submit = {onItemComplete(TodoItem(text, icon))setText("")}if (text.isBlank()) {setIcon(TodoIcon.Default)}Column {Row(Modifier.padding(horizontal = 16.dp).padding(top = 16.dp)) {//输入框TodoInputText(text = text,onTextChange = setText,//setText相当于onTextChange{ text=it }他这里用了语法糖modifier = Modifier.weight(1f).padding(end = 8.dp),onImeAction = submit)//按钮TodoEditText(onClick = {submit()},text = "Add",modifier = Modifier.align(Alignment.CenterVertically),enabled = text.isNotBlank())}AnimatedIconRow(icon = icon, {setIcon(it)}, Modifier.padding(top = 10.dp),iconsVisible)Text(text = "测试")}}

5.输入框背景

package com.jmj.jetpackcomposestate.todo.threeimport androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.FastOutLinearInEasing
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.TweenSpec
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButtonColors
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.unit.dp
import com.jmj.jetpackcomposestate.todo.TodoIcon
import com.jmj.jetpackcomposestate.todo.TodoItem// 顶部输入框 加上一个 灰色背景
@Composable
fun TodoItemInputBackground(elevate: Boolean,//如果为True  就有一个阴影边框modifier: Modifier = Modifier,content: @Composable RowScope.() -> Unit
) {//帧动画的形式展现Surface底部的阴影val animatedElevation by animateDpAsState(if (elevate) 1.dp else 0.dp ,TweenSpec(500))Surface(color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.05f),//设置 背景容器颜色,为黑色,透明度为0.05f//Surface 面版 底部有一个小小的阴影shadowElevation = animatedElevation, //一个委托 当发生改变的时候重构建组件shape = RectangleShape //设置阴影 展示动画 1dp 长方形) {Row(modifier = modifier.animateContentSize(animationSpec = TweenSpec(300)),content = content)}
}//输入框
@OptIn(ExperimentalMaterial3Api::class, ExperimentalComposeUiApi::class)
@Composable
fun TodoInputText(text: String,onTextChange: (String) -> Unit,modifier: Modifier = Modifier,onImeAction: () -> Unit = { }
) {val keyboardController = LocalSoftwareKeyboardController.current//输入框TextField(value = text,onValueChange = onTextChange,colors = TextFieldDefaults.textFieldColors(containerColor = Color.Transparent),maxLines = 1,modifier = modifier,//配置软件盘keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done),keyboardActions = KeyboardActions(onDone = {//点击完成之后的回调函数onImeAction()//隐藏软键盘keyboardController?.hide()}))}//按钮
@Composable
fun TodoEditText(onClick: () -> Unit,text: String,modifier: Modifier = Modifier,enabled: Boolean = true
) {TextButton(onClick = onClick,shape = CircleShape,colors = ButtonDefaults.buttonColors(),modifier = modifier,enabled = enabled) {Text(text = text)}}//一排图标 ,根据文本框是否有内容,自动收起和弹出,带动画效果
@Composable
fun AnimatedIconRow(icon: TodoIcon,onIconChange: (TodoIcon) -> Unit,modifier: Modifier = Modifier,visible: Boolean = true //可见性 状态  根据我们输入是否有内容来判度是否显示
) {val enter = remember {fadeIn(animationSpec = TweenSpec(300, easing = FastOutLinearInEasing)) //300ms打开 ,预定效果器}//淡入动画val exit = remember {fadeOut(animationSpec = TweenSpec(100, easing = FastOutSlowInEasing))}//淡出动画Box(modifier = modifier.defaultMinSize(minHeight = 16.dp)) {//默认最小高度16dpAnimatedVisibility(visible = visible,enter = enter,//进入exit = exit //退出) {//动画效果IconRow(icon = icon, onIconChange = onIconChange)}}}@Composable
fun IconRow(icon: TodoIcon,onIconChange: (TodoIcon) -> Unit,modifier: Modifier = Modifier
) {LazyRow(modifier = modifier) {val itemsIcon = TodoIcon.values() + TodoIcon.values()items(items = itemsIcon) {SelectableIconButton(icon = it.imageVector,iconContentDescription = it.contentDescription,onIconSelected = { onIconChange(it) },isSelected = (it == icon))}
//        for (todoIcon in TodoIcon.values()) {
//            SelectableIconButton(
//                icon = todoIcon.imageVector,
//                iconContentDescription = todoIcon.contentDescription,
//                onIconSelected = { onIconChange(todoIcon) },
//                isSelected = (todoIcon == icon)
//
//            )
//        }}}@Composable
fun SelectableIconButton(icon: ImageVector,iconContentDescription: Int,onIconSelected: () -> Unit,isSelected: Boolean,modifier: Modifier = Modifier
) {//图标选中和未选中状态,颜色是不一样的val tint = if (isSelected) {//选择之后的颜色MaterialTheme.colorScheme.primary   //蓝色} else {MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f) //黑色}TextButton(onClick = { onIconSelected() },shape = CircleShape,modifier = modifier) {Column {Icon(imageVector = icon,tint = tint,contentDescription = stringResource(id = iconContentDescription))if (isSelected) {//如果被选中了  下划线Box(modifier = Modifier.padding(top = 3.dp).width(icon.defaultWidth).height(1.dp).background(tint))} else {Spacer(modifier = Modifier.height(4.dp))}}}}@Composable
fun TodoItemEntryInput(onItemComplete: (TodoItem) -> Unit){val (text, setText) = remember { mutableStateOf("") } //屏幕旋转之后不会会保存值val (icon, setIcon) = remember { mutableStateOf(TodoIcon.Default) }val iconsVisible = text.isNotBlank()//点击 "add" 按钮,提交要做的事情val submit = {onItemComplete(TodoItem(text, icon))setText("")}TodoItemInput(text = text,onTextChange = setText,icon = icon,onIconChange = setIcon,submit = submit,iconsVisible = iconsVisible){TodoEditText(onClick = {submit()},text = "Add",modifier = Modifier.align(Alignment.CenterVertically),enabled = text.isNotBlank())}}@Composable
fun TodoItemInput(text: String,onTextChange: (String) -> Unit,icon: TodoIcon, onIconChange: (TodoIcon) -> Unit,submit: () -> Unit,iconsVisible: Boolean,buttonSlot : @Composable RowScope.() -> Unit
) {if (text.isBlank()) {onIconChange(TodoIcon.Default)}Column {Row(Modifier.padding(horizontal = 16.dp).padding(top = 16.dp)) {//输入框TodoInputText(text = text,onTextChange = onTextChange,//setText相当于onTextChange{ text=it }他这里用了语法糖modifier = Modifier.weight(1f).padding(end = 8.dp),onImeAction = submit)//按钮buttonSlot()}AnimatedIconRow(icon = icon, {onIconChange(it)}, Modifier.padding(top = 10.dp), iconsVisible)}}

package com.jmj.jetpackcomposestate.todo.threeimport androidx.compose.foundation.clickable
import com.jmj.jetpackcomposestate.todo.TodoItemimport androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.jmj.jetpackcomposestate.util.generateRandomTodoItem@Composable
fun TodoScreen(items:List<TodoItem>,onAddItem: (TodoItem) ->Unit,onRemoveItem: (TodoItem) ->Unit
){Column() {//输入框 ,外加一个灰色背景TodoItemInputBackground(elevate = true) {TodoItemEntryInput(onItemComplete = onAddItem )}LazyColumn(modifier = Modifier.weight(1f),//优先修饰 列表的布局contentPadding = PaddingValues(top = 8.dp)){items(items){TodoRow(todo = it, modifier = Modifier.fillParentMaxWidth(), onItemClicked = {onRemoveItem(it)})}}Button(onClick = {onAddItem(generateRandomTodoItem())},modifier = Modifier.padding(16.dp).fillMaxWidth()) {Text(text = "Add random item" )}}}@Composable
fun TodoRow(todo: TodoItem,onItemClicked:(TodoItem) -> Unit,modifier: Modifier = Modifier,){Row(modifier = modifier.clickable {onItemClicked(todo)}.padding(horizontal = 16.dp, vertical = 8.dp),horizontalArrangement = Arrangement.SpaceBetween  //子元素水平均匀分布) {Text(text = todo.task)Icon(imageVector = todo.icon.imageVector,contentDescription = stringResource(id = todo.icon.contentDescription))//stringResource去到strings.xml文件里去找到对应的字符串 描述}}

6.编辑模式

TodoScreen

package com.jmj.jetpackcomposestate.todo.fourimport androidx.compose.foundation.clickable
import com.jmj.jetpackcomposestate.todo.TodoItemimport androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.jmj.jetpackcomposestate.util.generateRandomTodoItem
import kotlin.random.Random@Composable
fun TodoScreen(items: List<TodoItem>,currentlyEditing: TodoItem?,onAddItem: (TodoItem) -> Unit,onRemoveItem: (TodoItem) -> Unit,onStartEdit: (TodoItem) -> Unit,onEditItemChange: (TodoItem) -> Unit,onEditDone: () -> Unit // 完成
) {Column() {// 当currentlyEditing(当前编辑条目)  为空是,显示添加输入框//否则进入编辑状态时,最顶部 会显示 "Editing item "文本val enableTopSection = (currentlyEditing == null)//输入框 ,外加一个灰色背景TodoItemInputBackground(elevate = true) {if (enableTopSection){TodoItemEntryInput(onItemComplete = onAddItem)}else{Text(text = "Editing item",style = MaterialTheme.typography.titleLarge,textAlign = TextAlign.Center,//文字水平居中modifier = Modifier.align(Alignment.CenterVertically)//控件垂直居中.padding(16.dp).fillMaxWidth())}}LazyColumn(modifier = Modifier.weight(1f),//优先修饰 列表的布局contentPadding = PaddingValues(top = 8.dp) //内容边距) {items(items) { todo ->if (currentlyEditing?.id == todo.id) {TodoItemInlineEditor(item = todo,onEditItemChange = onEditItemChange,onEditDone = onEditDone,onRemoveItem = onRemoveItem)} else {TodoRow(todo = todo,modifier = Modifier.fillParentMaxWidth(),onItemClicked = { onStartEdit(todo) })}}}Button(onClick = {onAddItem(generateRandomTodoItem())},modifier = Modifier.padding(16.dp).fillMaxWidth()) {Text(text = "Add random item")}}}@Composable
fun TodoRow(todo: TodoItem,onItemClicked: (TodoItem) -> Unit,modifier: Modifier = Modifier,) {val alpha = rememberSaveable{Random.nextFloat().coerceIn(0.3f,0.9f)}Row(modifier = modifier.clickable {onItemClicked(todo)}.padding(horizontal = 16.dp, vertical = 8.dp),horizontalArrangement = Arrangement.SpaceBetween  //子元素水平均匀分布) {Text(text = todo.task)Icon(imageVector = todo.icon.imageVector,contentDescription = stringResource(id = todo.icon.contentDescription),modifier=Modifier.alpha(alpha))//stringResource去到strings.xml文件里去找到对应的字符串 描述}}

TodoViewModle

package com.jmj.jetpackcomposestate.todo.fourimport androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.jmj.jetpackcomposestate.todo.TodoItem/*** 状态容器*/
class TodoViewModel : ViewModel() {//TodoItems集合只读var todoItems = mutableStateListOf<TodoItem>()private set//当前正在编辑的TodoItem 的索引位置private var currentEditPostion by mutableStateOf(-1)//当前正在编辑的TodoItem 的对象val currentEditItem: TodoItem? get() = todoItems.getOrNull(currentEditPostion)fun addItem(item: TodoItem) {//添加todoItems.add(item)//因为是封装了状态对象,所以改变值会自动重构组件,调用此状态的组件}fun removeItem(item: TodoItem) {//删除todoItems.remove(item)onEditDone() //删除结束一个集合 把状态置 为-1 代表当前没有被选中的编辑条目}/*** 编辑完成的函数*/fun onEditDone() {currentEditPostion = -1}//当TodoItem 列表中的条目 被选中时,传入该对象,获取它在列表中的索引位置fun onEditItemSelected(item: TodoItem){currentEditPostion = todoItems.indexOf(item)}//TodoItem编辑完成,重新给集合中的TodoItem赋值//id 属性值不能修改 ,进行校验fun onEditItemChange(item: TodoItem){val  currentItem =    requireNotNull(currentEditItem) //空抛异常require(currentItem.id == item.id){//false 往这里走"You can only change an item with the same id as currentEditItem"}todoItems[currentEditPostion] = item}}

TodoComponents

package com.jmj.jetpackcomposestate.todo.fourimport androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateContentSize
import androidx.compose.animation.core.FastOutLinearInEasing
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.TweenSpec
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import com.jmj.jetpackcomposestate.todo.TodoIcon
import com.jmj.jetpackcomposestate.todo.TodoItem/*** 当TodoItem 列表中的条目被选中时,会弹出一个输入框,用于编辑选中TodoItem 的信息* @param item 选中的TodoItem项目* @param onEditItemChange 编辑条目时的回调* @param onEditDone 编辑完成时的回调* @param onRemoveItem 删除条目 时的回调**/
@Composable
fun TodoItemInlineEditor(item: TodoItem,onEditItemChange:(TodoItem) ->Unit,onEditDone: () -> Unit ,onRemoveItem: (TodoItem) -> Unit
){TodoItemInput(text = item.task,onTextChange = {onEditItemChange(item.copy(task = it))},//it 为改变的 text 文本icon = item.icon,onIconChange = { onEditItemChange(item.copy(icon = it))  } ,//it 为改变的 icon 图标submit = onEditDone ,iconsVisible = true ,buttonSlot = {//保存和删除两个图标Row {val shrinkButtons = Modifier.widthIn(20.dp)TextButton(onClick = onEditDone, modifier = shrinkButtons) {Text(text =  "\uD83D\uDCBE", //Emoji 符号 ,软盘textAlign = TextAlign.End)}TextButton(onClick = {onRemoveItem(item)}, modifier = shrinkButtons) {Text(text =  "×",textAlign = TextAlign.End,color =  Color.Red)}}})}// 顶部输入框 加上一个 灰色背景
@Composable
fun TodoItemInputBackground(elevate: Boolean,//如果为True  就有一个阴影边框modifier: Modifier = Modifier,content: @Composable RowScope.() -> Unit
) {//帧动画的形式展现Surface底部的阴影val animatedElevation by animateDpAsState(if (elevate) 1.dp else 0.dp ,TweenSpec(500))Surface(color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.05f),//设置 背景容器颜色,为黑色,透明度为0.05f//Surface 面版 底部有一个小小的阴影shadowElevation = animatedElevation, //一个委托 当发生改变的时候重构建组件shape = RectangleShape //设置阴影 展示动画 1dp 长方形) {Row(modifier = modifier.animateContentSize(animationSpec = TweenSpec(300)),content = content)}
}//输入框
@OptIn(ExperimentalMaterial3Api::class, ExperimentalComposeUiApi::class)
@Composable
fun TodoInputText(text: String,onTextChange: (String) -> Unit,modifier: Modifier = Modifier,onImeAction: () -> Unit = { }
) {val keyboardController = LocalSoftwareKeyboardController.current//输入框TextField(value = text,onValueChange = onTextChange,colors = TextFieldDefaults.textFieldColors(containerColor = Color.Transparent),maxLines = 1,modifier = modifier,//配置软件盘keyboardOptions = KeyboardOptions.Default.copy(imeAction = ImeAction.Done),keyboardActions = KeyboardActions(onDone = {//点击完成之后的回调函数onImeAction()//隐藏软键盘keyboardController?.hide()}))}//按钮
@Composable
fun TodoEditButton(onClick: () -> Unit,text: String,modifier: Modifier = Modifier,enabled: Boolean = true
) {TextButton(onClick = onClick,shape = CircleShape,colors = ButtonDefaults.buttonColors(),modifier = modifier,enabled = enabled) {Text(text = text)}}//一排图标 ,根据文本框是否有内容,自动收起和弹出,带动画效果
@Composable
fun AnimatedIconRow(icon: TodoIcon,onIconChange: (TodoIcon) -> Unit,modifier: Modifier = Modifier,visible: Boolean = true //可见性 状态  根据我们输入是否有内容来判度是否显示
) {val enter = remember {fadeIn(animationSpec = TweenSpec(300, easing = FastOutLinearInEasing)) //300ms打开 ,预定效果器}//淡入动画val exit = remember {fadeOut(animationSpec = TweenSpec(100, easing = FastOutSlowInEasing))}//淡出动画Box(modifier = modifier.defaultMinSize(minHeight = 16.dp)) {//默认最小高度16dpAnimatedVisibility(visible = visible,enter = enter,//进入exit = exit //退出) {//动画效果IconRow(icon = icon, onIconChange = onIconChange)}}}@Composable
fun IconRow(icon: TodoIcon,onIconChange: (TodoIcon) -> Unit,modifier: Modifier = Modifier
) {LazyRow(modifier = modifier) {val itemsIcon = TodoIcon.values() + TodoIcon.values()items(items = itemsIcon) {SelectableIconButton(icon = it.imageVector,iconContentDescription = it.contentDescription,onIconSelected = { onIconChange(it) },isSelected = (it == icon))}
//        for (todoIcon in TodoIcon.values()) {
//            SelectableIconButton(
//                icon = todoIcon.imageVector,
//                iconContentDescription = todoIcon.contentDescription,
//                onIconSelected = { onIconChange(todoIcon) },
//                isSelected = (todoIcon == icon)
//
//            )
//        }}}@Composable
fun SelectableIconButton(icon: ImageVector,iconContentDescription: Int,onIconSelected: () -> Unit,isSelected: Boolean,modifier: Modifier = Modifier
) {//图标选中和未选中状态,颜色是不一样的val tint = if (isSelected) {//选择之后的颜色MaterialTheme.colorScheme.primary   //蓝色} else {MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f) //黑色}TextButton(onClick = { onIconSelected() },shape = CircleShape,modifier = modifier) {Column {Icon(imageVector = icon,tint = tint,contentDescription = stringResource(id = iconContentDescription)// 描述 就是残障人,需要语音播报,然后通过Id找到strings.xml下的字符串播报)if (isSelected) {//如果被选中了  下划线Box(modifier = Modifier.padding(top = 3.dp).width(icon.defaultWidth).height(1.dp).background(tint))} else {Spacer(modifier = Modifier.height(4.dp))}}}}@Composable
fun TodoItemEntryInput(onItemComplete: (TodoItem) -> Unit){val (text, setText) = remember { mutableStateOf("") } //屏幕旋转之后不会会保存值val (icon, setIcon) = remember { mutableStateOf(TodoIcon.Default) }val iconsVisible = text.isNotBlank()//点击 "add" 按钮,提交要做的事情val submit = {onItemComplete(TodoItem(text, icon))setText("")}TodoItemInput(text = text,onTextChange = setText,icon = icon,onIconChange = setIcon,submit = submit,iconsVisible = iconsVisible){TodoEditButton(onClick = submit,text ="Add",enabled = iconsVisible)}}@Composable
fun TodoItemInput(text: String,onTextChange: (String) -> Unit,icon: TodoIcon,onIconChange: (TodoIcon) -> Unit,submit: () -> Unit,iconsVisible: Boolean,//最右侧的图标 与 按钮 在编辑时 ,会有删除和保存两个图标,添加时会有一个"Add" 按钮buttonSlot : @Composable ()-> Unit) {if (text.isBlank()) {onIconChange(TodoIcon.Default)}Column {Row(Modifier.padding(horizontal = 16.dp).padding(top = 16.dp)) {//输入框TodoInputText(text = text,onTextChange = onTextChange,//setText相当于onTextChange{ text=it }他这里用了语法糖modifier = Modifier.weight(1f).padding(end = 8.dp),onImeAction = submit)Spacer(modifier = Modifier.width(8.dp))//垂直居中Box(modifier = Modifier.align(Alignment.CenterVertically)){ buttonSlot() }}AnimatedIconRow(icon = icon, {onIconChange(it)}, Modifier.padding(top = 10.dp), iconsVisible)}}

TodoItem

package com.jmj.jetpackcomposestate.todo;import androidx.annotation.StringRes
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CropSquare
import androidx.compose.material.icons.filled.Done
import androidx.compose.material.icons.filled.Event
import androidx.compose.material.icons.filled.PrivacyTip
import androidx.compose.material.icons.filled.RestoreFromTrash
import androidx.compose.material.icons.filled.Square
import androidx.compose.ui.graphics.vector.ImageVector
import com.jmj.jetpackcomposestate.R
import java.util.UUIDdata class TodoItem(val task:String,val icon:TodoIcon = TodoIcon.Default,val id:UUID=UUID.randomUUID())enum class TodoIcon(val imageVector: ImageVector,@StringRes val contentDescription: Int
){//使用了 Material Design 的图标Square(Icons.Default.CropSquare, R.string.cd_expand),Done(Icons.Default.Done, R.string.cd_done),Event(Icons.Default.Event, R.string.cd_event),Privacy(Icons.Default.PrivacyTip, R.string.cd_privacy),Trash(Icons.Default.RestoreFromTrash, R.string.cd_restore);companion object {val Default = Square}}

TodoAcitivity

package com.jmj.jetpackcomposestate.todoimport android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import com.jmj.jetpackcomposestate.todo.four.TodoViewModel
import com.jmj.jetpackcomposestate.todo.four.TodoScreenimport com.jmj.jetpackcomposestate.ui.theme.JetpackComposeStateThemeclass TodoActivity : ComponentActivity() {private val todoViewModel by viewModels<TodoViewModel>()override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContent {JetpackComposeStateTheme {TodoActivityScreen()}}}@Composableprivate fun TodoActivityScreen() {TodoScreen(items=todoViewModel.todoItems,currentlyEditing = todoViewModel.currentEditItem,onAddItem = todoViewModel::addItem,onRemoveItem = todoViewModel::removeItem,onStartEdit = todoViewModel::onEditItemSelected,onEditItemChange = todoViewModel::onEditItemChange,onEditDone = todoViewModel::onEditDone)}
}

7.状态恢复

parcelize要用的话需要插件

pluginManagement {repositories {google()mavenCentral()gradlePluginPortal()}//插件plugins{id("com.android.application")version("7.1.0-alpha05")id("com.android.library")version("7.1.0-alpha05")id("org.jetbrains.kotlin.android")version("1.5.10")id("org.jetbrains.kotlin.plugin.parcelize")version("1.5.10")}}
dependencyResolutionManagement {repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)repositories {google()mavenCentral()}
}rootProject.name = "JetpackComposeState"
include(":app")

这里翻墙了才下载下来的

接下一章

这篇关于JetpackCompose 之 状态学习的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/655019

相关文章

Java进阶学习之如何开启远程调式

《Java进阶学习之如何开启远程调式》Java开发中的远程调试是一项至关重要的技能,特别是在处理生产环境的问题或者协作开发时,:本文主要介绍Java进阶学习之如何开启远程调式的相关资料,需要的朋友... 目录概述Java远程调试的开启与底层原理开启Java远程调试底层原理JVM参数总结&nbsMbKKXJx

Flutter监听当前页面可见与隐藏状态的代码详解

《Flutter监听当前页面可见与隐藏状态的代码详解》文章介绍了如何在Flutter中使用路由观察者来监听应用进入前台或后台状态以及页面的显示和隐藏,并通过代码示例讲解的非常详细,需要的朋友可以参考下... flutter 可以监听 app 进入前台还是后台状态,也可以监听当http://www.cppcn

MySQL 中的服务器配置和状态详解(MySQL Server Configuration and Status)

《MySQL中的服务器配置和状态详解(MySQLServerConfigurationandStatus)》MySQL服务器配置和状态设置包括服务器选项、系统变量和状态变量三个方面,可以通过... 目录mysql 之服务器配置和状态1 MySQL 架构和性能优化1.1 服务器配置和状态1.1.1 服务器选项

Java深度学习库DJL实现Python的NumPy方式

《Java深度学习库DJL实现Python的NumPy方式》本文介绍了DJL库的背景和基本功能,包括NDArray的创建、数学运算、数据获取和设置等,同时,还展示了如何使用NDArray进行数据预处理... 目录1 NDArray 的背景介绍1.1 架构2 JavaDJL使用2.1 安装DJL2.2 基本操

linux进程D状态的解决思路分享

《linux进程D状态的解决思路分享》在Linux系统中,进程在内核模式下等待I/O完成时会进入不间断睡眠状态(D状态),这种状态下,进程无法通过普通方式被杀死,本文通过实验模拟了这种状态,并分析了如... 目录1. 问题描述2. 问题分析3. 实验模拟3.1 使用losetup创建一个卷作为pv的磁盘3.

Java实现状态模式的示例代码

《Java实现状态模式的示例代码》状态模式是一种行为型设计模式,允许对象根据其内部状态改变行为,本文主要介绍了Java实现状态模式的示例代码,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来... 目录一、简介1、定义2、状态模式的结构二、Java实现案例1、电灯开关状态案例2、番茄工作法状态案例

通过prometheus监控Tomcat运行状态的操作流程

《通过prometheus监控Tomcat运行状态的操作流程》文章介绍了如何安装和配置Tomcat,并使用Prometheus和TomcatExporter来监控Tomcat的运行状态,文章详细讲解了... 目录Tomcat安装配置以及prometheus监控Tomcat一. 安装并配置tomcat1、安装

Linux之进程状态&&进程优先级详解

《Linux之进程状态&&进程优先级详解》文章介绍了操作系统中进程的状态,包括运行状态、阻塞状态和挂起状态,并详细解释了Linux下进程的具体状态及其管理,此外,文章还讨论了进程的优先级、查看和修改进... 目录一、操作系统的进程状态1.1运行状态1.2阻塞状态1.3挂起二、linux下具体的状态三、进程的

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

Ilya-AI分享的他在OpenAI学习到的15个提示工程技巧

Ilya(不是本人,claude AI)在社交媒体上分享了他在OpenAI学习到的15个Prompt撰写技巧。 以下是详细的内容: 提示精确化:在编写提示时,力求表达清晰准确。清楚地阐述任务需求和概念定义至关重要。例:不用"分析文本",而用"判断这段话的情感倾向:积极、消极还是中性"。 快速迭代:善于快速连续调整提示。熟练的提示工程师能够灵活地进行多轮优化。例:从"总结文章"到"用