Kotlin——jetpackCompose按钮弹出dialog、列表(类似recyclerView)、双向绑定--列表(可单选/多选)、列表选中显示边框(最简单的方式)

一、按钮弹出dialog

效果图为:

Kotlin——jetpackCompose按钮弹出dialog、列表(类似recyclerView)、双向绑定--列表(可单选/多选)、列表选中显示边框(最简单的方式)_第1张图片

package com.example.jetpackcompose

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import com.example.jetpackcompose.ui.theme.JetpackComposeTheme

class MainActivity : ComponentActivity() {
    private lateinit var openDialog: MutableState
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            JetpackComposeTheme {
                Surface(color = MaterialTheme.colors.background) {
                    openDialog = remember {
                        mutableStateOf(false)
                    }
                    addAlterDialog(openDialog = openDialog)
                    addButton(openDialog = openDialog)

                }
            }
        }
    }
}

@Composable
fun addButton(openDialog: MutableState) {
    Button(onClick = { openDialog.value = true }) {
        Text(text = "点击弹窗")
    }
}

@Composable
fun addAlterDialog(openDialog: MutableState) {
    if (openDialog.value) {
        AlertDialog(
            onDismissRequest = { openDialog.value = false },
            title = { Text(text = "标题") },
            text = {
                Text(
                    text = "文本内容"
                )
            }, confirmButton = {
                TextButton(onClick = { openDialog.value = false }) {
                    Text(text = "确认")
                }
            }, dismissButton = {
                TextButton(onClick = { openDialog.value = false }) {
                    Text(text = "取消")
                }
            })
    }
}

二、列表(类似recyclerView)

效果图:

Kotlin——jetpackCompose按钮弹出dialog、列表(类似recyclerView)、双向绑定--列表(可单选/多选)、列表选中显示边框(最简单的方式)_第2张图片

MainActivity代码:

class MainActivity : ComponentActivity() {
    //定义数据集合
    val itemsList = (0..10).toList()

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

        setContent {
            ComposeRecyclerViewTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    PuppyListItem(itemsList)
                }
            }
        }
    }
}
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun PuppyListItem(itemsList: List) {
    LazyColumn(
        Modifier.fillMaxHeight(),
        //设置Padding为20dp
        contentPadding = PaddingValues(horizontal = 20.dp, vertical = 20.dp),
        //设置item的间距为10dp
//        verticalArrangement = Arrangement.spacedBy(10.dp)

    ) {
        //添加多个item,回调中没有数据的下标
        items(itemsList.size) {
            Card(onClick = { Log.i("TAG", "点击==>$it") }) {
                Text("第$it 个Item")
            }
        }

    }


}

3、双向绑定--列表(可单选/多选)

效果图:

Kotlin——jetpackCompose按钮弹出dialog、列表(类似recyclerView)、双向绑定--列表(可单选/多选)、列表选中显示边框(最简单的方式)_第3张图片

代码 

MainActivity
class MainActivity : ComponentActivity() {
    //定义数据集合

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

        setContent {

            ComposeRecyclerViewTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    PuppyListItem()
                }
            }
        }
    }


}
MainViewModel
class MainViewModel : ViewModel() {

    var displayList = mutableStateListOf()

    init {
        displayList = MockData.getStateListData()
    }


    fun handleClickItem(position: Int) {

//        danxuan(position)
        duoxuan(position)
    }

    /**
     * 单选
     */
    fun danxuan(position: Int) {
        var indexOther = -1
        displayList.forEachIndexed { index, projectBean ->
            // 如果有其他项被选中
            if (projectBean.isSelect && index != position) {
                indexOther = index
            }
        }
        if (indexOther != -1) {// 如果有其他项被选中
            displayList[indexOther] =
                displayList[indexOther].copy(isSelect = false) // 改变为未选中,不能放在for循环,不然会crash,原因未知
        }


        // 本身显示选中(或取消选中)
        val item = displayList[position]
        displayList[position] = item.copy(isSelect = !item.isSelect)
    }

    /**
     * 多选
     */
    fun duoxuan(position: Int) {
        // 本身显示选中(或取消选中)
        val item = displayList[position]
        displayList[position] = item.copy(isSelect = !item.isSelect)
    }
}
import android.util.Log
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.Card
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.composerecyclerview.bean.ProjectBean
import com.example.composerecyclerview.viewmodel.MainViewModel


@Composable
fun PuppyListItem(mainViewModel: MainViewModel = viewModel()) {
    LazyColumn(Modifier.fillMaxHeight()) {
        //添加多个item,回调中没有数据的下标
        items(mainViewModel.displayList.size) {
            itemLayout(mainViewModel.displayList[it], it){item->
                mainViewModel.handleClickItem(item)
            }
        }
    }
}

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun itemLayout(projectBean: ProjectBean, position: Int, click: (Int) -> Unit) {

    Card(
        modifier = Modifier
            .fillMaxSize()
            .padding(horizontal = 10.dp, vertical = 5.dp),
        border = if (projectBean.isSelect) BorderStroke(0.5.dp, Color.Green)
        else BorderStroke(0.dp, Color.White),

        onClick = {
            Log.i("TAG", "点击==>$projectBean")
            click(position)
        }) {

        ConstraintLayout(modifier = Modifier.padding(10.dp)) {
            val (title, subtime) = createRefs()
            Text(
                text = "项目名称:${projectBean.name}",
                modifier = Modifier.constrainAs(title) {
                    // 位置:顶部对图片顶部,左对图片右,底对副标题顶部
                    top.linkTo(parent.top)
                    start.linkTo(parent.start)
                    bottom.linkTo(subtime.top)
                }
            )
            Text(
                text = projectBean.time,
                modifier = Modifier.constrainAs(subtime) {
                    // 位置:顶部对图片顶部,左对图片右,底对副标题顶部
                    top.linkTo(title.bottom)
                    bottom.linkTo(parent.bottom)
                    start.linkTo(parent.start)
                }
            )
        }
    }
}
ProjectBean
data class ProjectBean(
    var name: String = "",
    var time: String = "",
    var isSelect: Boolean = false
)

MockData
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.snapshots.SnapshotStateList
import com.example.composerecyclerview.bean.ProjectBean

// MutableList
object MockData {
    fun getStateListData(): SnapshotStateList {
        val list = mutableStateListOf()
        repeat(5) {
            val projectBean = ProjectBean("疫苗$it", "2023/02/26")
            list.add(projectBean)
        }
        return list
    }

    fun getListData(): MutableList {
        val list = mutableListOf()
        repeat(5) {
            val projectBean = ProjectBean("疫苗$it", "2023/02/26")
            list.add(projectBean)
        }
        return list
    }
}

完整代码下载地址:https://download.csdn.net/download/wy313622821/87602879

4、列表选中显示边框(最简单的方式)

效果图:

Kotlin——jetpackCompose按钮弹出dialog、列表(类似recyclerView)、双向绑定--列表(可单选/多选)、列表选中显示边框(最简单的方式)_第4张图片

代码:

@Composable
fun MyList() {
    val items = listOf("Item 1", "Item 2", "Item 3")
    val selectedIndex = remember { mutableStateOf(0) } // 记录选中的索引

    Column(
        modifier = Modifier.padding(10.dp)
    ) {
        items.forEachIndexed { index, item ->

            Box(
                modifier = Modifier
                    .border(if (index == selectedIndex.value) 1.dp else (-1).dp, Color.Blue) // 设置成-1才没有边框
                    .clickable(onClick = { selectedIndex.value = index })
                    .padding(16.dp)

            ) {
                Row {
                    Text(text = "$index - ")
                    Text(text = item)
                }
            }
        }
    }
}

 

你可能感兴趣的:(kotlin,-,java,kotlin,android,java)