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


    JetpackComposeState
    Expand
    Collapse
    Crop
    Done
    Event
    Privacy
    Restored

themes.xml




    

JetpackCompose 之 状态学习_第1张图片

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
){

    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)
    }
}

JetpackCompose 之 状态学习_第2张图片JetpackCompose 之 状态学习_第3张图片

JetpackCompose 之 状态学习_第4张图片

JetpackCompose 之 状态学习_第5张图片 JetpackCompose 之 状态学习_第6张图片

JetpackCompose 之 状态学习_第7张图片

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())  //这是一个状态

    val  todoItems:LiveData> = _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,
    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()

    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 by todoViewModel.todoItems.observeAsState(initial = listOf())



        TodoScreen(
            items=items,
            onAddItem = {  todoViewModel.addItem(it) },
            onRemoveItem = {todoViewModel.removeItem(it)}
            )

    }
}

JetpackCompose 之 状态学习_第8张图片

JetpackCompose 之 状态学习_第9张图片JetpackCompose 之 状态学习_第10张图片JetpackCompose 之 状态学习_第11张图片

2.重组

JetpackCompose 之 状态学习_第12张图片 JetpackCompose 之 状态学习_第13张图片

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,
    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)
}

 JetpackCompose 之 状态学习_第14张图片

JetpackCompose 之 状态学习_第15张图片 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
     *  它是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()

            )


        }


    }


}

JetpackCompose 之 状态学习_第16张图片

JetpackCompose 之 状态学习_第17张图片JetpackCompose 之 状态学习_第18张图片JetpackCompose 之 状态学习_第19张图片

 做出下面的选择按钮

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
     *  它是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 = "测试")


    }


}

JetpackCompose 之 状态学习_第20张图片

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
     *  它是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 = "测试")


    }


}

JetpackCompose 之 状态学习_第21张图片

5.输入框背景

JetpackCompose 之 状态学习_第22张图片

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,
    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,
    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()
        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()

    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
        )

    }
}

JetpackCompose 之 状态学习_第23张图片

7.状态恢复

JetpackCompose 之 状态学习_第24张图片

parcelize要用的话需要插件

JetpackCompose 之 状态学习_第25张图片

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 之 状态学习_第26张图片

JetpackCompose 之 状态学习_第27张图片

这里了才下载下来的

接下一章

你可能感兴趣的:(Androd,Jetpack,Compose,android)