JetpackCompose 之 状态学习

news2024/11/19 19:34:58

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.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.tiger.jetpackcomposestate.R
import java.util.UUID

data 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.one

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.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.one

import 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.JetpackComposeStateTheme

class TodoActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            JetpackComposeStateTheme {

                TodoActivityScreen()
            }
        }
    }

    @Composable
    private 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.one

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.jmj.jetpackcomposestate.todo.TodoItem

class TodoViewModel:ViewModel(){

    private var _todoItems = MutableLiveData(listOf<TodoItem>())  //这是一个状态

    val  todoItems:LiveData<List<TodoItem>> = _todoItems

    fun 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.one

import androidx.compose.foundation.clickable
import com.jmj.jetpackcomposestate.todo.TodoItem


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.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.one

import 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.JetpackComposeStateTheme


class TodoActivity : ComponentActivity() {

    private val todoViewModel by viewModels<TodoViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            JetpackComposeStateTheme {

                TodoActivityScreen()
            }
        }
    }

    @Composable
    private 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.one


import 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.one


import 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.one


import 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)) {//默认最小高度16dp
        AnimatedVisibility(
            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.two


import 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)) {//默认最小高度16dp
        AnimatedVisibility(
            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.three


import 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)) {//默认最小高度16dp
        AnimatedVisibility(
            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.three

import androidx.compose.foundation.clickable
import com.jmj.jetpackcomposestate.todo.TodoItem


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.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.four

import androidx.compose.foundation.clickable
import com.jmj.jetpackcomposestate.todo.TodoItem


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.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.four

import 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.four

import 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)) {//默认最小高度16dp
        AnimatedVisibility(
            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.UUID

data 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.todo

import 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.TodoScreen


import com.jmj.jetpackcomposestate.ui.theme.JetpackComposeStateTheme


class TodoActivity : ComponentActivity() {

    private val todoViewModel by viewModels<TodoViewModel>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            JetpackComposeStateTheme {
                TodoActivityScreen()
            }
        }
    }

    @Composable
    private 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")
 

这里翻墙了才下载下来的

接下一章

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1417251.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

MyBatis详解(3)-- 动态代理及映射器

MyBatis详解&#xff08;3&#xff09; mybatis 动态代理动态代理的规范selectOne和selectListnamespace mybatis映射器映射器的引入&#xff1a; 映射器的组成select 元素结构&#xff1a;单个参数传递多个参数传递 insert 元素结构主键回填&#xff1a;自定义主键生成规则 u …

CSS 双色拼接按钮效果

<template><view class="sss"><button> <!-- 按钮 --><view class="span"> 按钮 </view> <!-- 按钮文本 --></button></view></template><script></script><style>body {b…

JUC-ReentrantLock,ReentrantReadWriteLock,StampedLock

1. 概述 前面介绍过了synchronized关键字作用的锁升级过程 无锁->偏向锁->轻量锁->重锁 下面再介绍实现Lock接口的锁的升级过程 无锁->独占锁&#xff08;ReentrantLock&#xff0c;Synchronized&#xff09;->读写锁(ReentranReadWriteLock)->邮戳锁(Stamp…

app逆向-apktool逆向工具安装使用

文章目录 一、前言二、安装三、执行 一、前言 apktool是一个能够解析和分析安卓应用文件&#xff08;APK&#xff09;的工具&#xff0c;帮助了解应用程序的内部结构和功能。 二、安装 window版本 下载地址&#xff1a;版本2.9.3&#xff0c;并将下载的 jar 重命名为apktoo…

【缓存周总结】Redis缓存的使用以及数据安全的处理

前言 Redis非关系型数据库已经是很常见的工具了&#xff0c;项目中用到的也很多&#xff0c;这篇文章系统的分析下使用过程中可能会遇到的问题 一、缓存 缓存是数据交换的缓冲区&#xff0c;是存贮数据的临时地方&#xff0c;一般读写性能较高。 我们项目中引用的Redis目的就是…

SPI:JDK 与 SpringBoot

浅谈Java SPI原理与其在JDBC、Flink中的应用 API&#xff1a;由被调方提供的实现了某个完整功能的接口&#xff0c;主调方直接调用该接口来享用该功能&#xff0c;而无需关注该接口的具体实现。比如使用 JDK 的 InputStream#read 从文件系统中读取数据。 SPI&#xff1a;被调方…

DOM 型 XSS 攻击演示(附链接)

一、介绍 DOM&#xff08;Document Object Model&#xff09;型 XSS&#xff08;Cross-Site Scripting&#xff09;攻击是一种 Web 应用程序中的安全漏洞&#xff0c;其特点是攻击者成功地注入了恶意脚本&#xff0c;这些脚本在用户的浏览器中执行&#xff0c;从而导致恶意行为…

DETR解读,将Transformer带入CV

论文出处 [2005.12872] End-to-End Object Detection with Transformers (arxiv.org) 一个前置知识 匈牙利算法&#xff1a;来源于二部图匹配&#xff0c;计算最小或最大匹配 算法操作&#xff1a;在n*n的矩阵中 减去行列最小值&#xff0c;更新矩阵&#xff08;此时行或者…

C# RichTextBox常用属性、方法学习1

1 字体 Font font1 new Font("宋体", 18); richTextBox1.Font font1; Font font2 new Font("宋体", 10, FontStyle.Underline); richTextBox1.SelectionFont font2; 定义字体&#xff0c;可以带2个参数&#…

代码随想录刷题笔记-Day13

1. 二叉树的层序遍历 102. 二叉树的层序遍历https://leetcode.cn/problems/binary-tree-level-order-traversal/层次遍历依靠队列的先进先出特点实现。 解题思路 层序遍历的本质就是对每一个pop出来的处理节点&#xff0c;处理后把他的左右节点放进去。 对于每一层来说&…

菱形打印和十进制ip转二进制

1.菱形打印 用for循环 #!/bin/bashread -p "请输入菱形的大小&#xff1a;" num #打印向上的等腰三角形 for ((i1;i<num;i)) dofor ((jnum-1;j>i;j--))doecho -n " " #打印的是前面的空格donefor ((k1;k<2*i-1;k))doecho -n "*" #打印…

【stm32】hal库学习笔记-FSMC连接TFT_LCD

【stm32】hal库学习笔记-FSMC连接TFT LCD 触摸屏结构与原理 LCD模块接口原理图 LCD 接口连接在 FSMC 总线上面&#xff0c;图中的 T_MISO/T_MOSI/T_PEN/T_SCK/T_CS 连接在 MCU 的 PB2/PF11/PB1/PB0/PC13 上&#xff0c;这些信号用来实现对液晶触摸屏的控制&#xff08;支持电阻…

QT tcp与udp网络通信以及定时器的使用 (7)

QT tcp与udp网络通信以及定时器的使用 文章目录 QT tcp与udp网络通信以及定时器的使用1、QT网络与通信简单介绍2、QT TCP通信1、 服务器的流程2、 客户端的流程3、服务器的编写4、客户端的编写 3、QT UDP通信1、客户端流程2、客户端编写3、UDP广播4、UDP组播 4、定时器的用法1、…

leetcode刷题日志-146LRU缓存

思路&#xff1a;使用hashmap储存key&#xff0c;vaule&#xff0c;使用双向链表以快速查到尾结点&#xff08;待逐出的节点&#xff09;&#xff0c;链表的题一定要在纸上画一下&#xff0c;不然连着连着就不知道连在哪里去了 class LRUCache {public class ListNode {int ke…

【js基础】日期对象的使用,查找、增加、克隆、删除DOM节点,M端事件

文章目录 前言一、日期对象日期对象的作用1.1 实例化1.2 日期对象的方法1.3 时间的格式化1.4 时间戳的使用时间戳是什么js的时间戳 二、DOM的增删改查什么叫做DOM节点2.1 DOM的查找2.2 增加节点2.3 克隆节点和删除节点 三、M端事件3.1 M端是什么&#xff1f; 总结 前言 在 Jav…

你的MiniFilter安全吗?

简介 筛选器管理器 (FltMgr.sys)是Windows系统提供的内核模式驱动程序, 用于实现和公开文件系统筛选器驱动程序中通常所需的功能; 第三方文件系统筛选器开发人员可以使用FltMgr的功能可以更加简单的编写文件过滤驱动, 这种驱动我们通常称为MiniFilter, 下面是MiniFilter的基本…

STM32CubeMX教程31 USB_DEVICE - HID外设_模拟键盘或鼠标

目录 1、准备材料 2、实验目标 3、模拟鼠标实验流程 3.0、前提知识 3.1、CubeMX相关配置 3.1.0、工程基本配置 3.1.1、时钟树配置 3.1.2、外设参数配置 3.1.3、外设中断配置 3.2、生成代码 3.2.0、配置Project Manager页面 3.2.1、设初始化调用流程 3.2.2、外设中…

优选6款前端动画特效分享(附在线演示)

优选6款前端动画特效 其中有CSS动画、canvas动画、js小游戏等等 下方效果图可能不是特别的生动 那么你可以点击在线预览进行查看相应的动画特效 同时也是可以下载该资源的 翻页时钟特效 基于react实现的一款翻页时钟特效 切换时间特效跟比赛切换分数牌相似 以下效果图只能体现…

Gitlab7.14 中文版安装教程

Gitlab7.14 中文版安装教程 注&#xff1a; 本教程由羞涩梦整理同步发布&#xff0c;本人技术分享站点&#xff1a;blog.hukanfa.com转发本文请备注原文链接&#xff0c;本文内容整理日期&#xff1a;2024-01-28csdn 博客名称&#xff1a;五维空间-影子&#xff0c;欢迎关注 …

T05垃圾收集算法与垃圾收集器ParNew CMS

垃圾收集算法与垃圾收集器ParNew & CMS 垃圾收集算法 #### f 分代收集理论 当前虚拟机的垃圾收集都采用分代收集算法。根据对象存活周期不同将内存分为几块&#xff0c;一般将java堆分为新生代和老年代&#xff0c;然后根据各个年代的特点选择不同的垃圾收集算法。 在新…