简体   繁体   English

如何在主 Activity 中发生事件后重组可组合项?

[英]How to recompose a composable after an event occured in the main Activity?

I created an event listener to catch when a physical button is pressed, and it works well.我创建了一个事件侦听器来捕获按下物理按钮的时间,并且效果很好。 But I would want to update a list used in a LazyColumn但我想更新LazyColumn中使用的list

class MainActivity : ComponentActivity() {
   @OptIn(ExperimentalComposeUiApi::class)
   override fun onCreate(savedInstanceState: Bundle?) {
       super.onCreate(savedInstanceState)
       setContent {
           Theme {
               Surface(
                   modifier = Modifier                   .fillMaxSize(),
                   color = MaterialTheme.colors.background
               ) {
                   Column(modifier = Modifier.fillMaxSize()) {
                       Greeting("Android")
                   }
               }
           }
       }
   }

   @SuppressLint("RestrictedApi")
   override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
      // Handling event to get a text (type String)
      // ......

      //then updating my list
      myList+=newValue
   }


var myList: List<String> = mutableListOf()

@OptIn(ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class)
@Composable
fun Greeting(name: String, paramBarcode: String) {
   var mutableList by remember {mutableStateOf(myList)}
   
   Button(onClick = {
      myList+= "new item"
      mutableList = myList
   }) {
      Text(text = "Add")
   }

   LazyColumn(Modifier.fillMaxSize()            .padding(16.dp)
   ) {
       stickyHeader {Row(Modifier.fillMaxSize()                  .background(Color.Green)
           ) {
               TableCell(text = "Code", width = 264)
           }
       }
       itemsIndexed(items = mutableList, itemContent = {
          index, item ->
           Row(Modifier.fillMaxSize(),
           ) {
               TableCell(text = item, width = 256)
           }
       })
   }
}

If I try to add or remove an element of the list from my composable, everything is fine, but I can't get the same behaviour from my event.如果我尝试从我的可组合项中addremove list的元素,一切都很好,但我无法从我的事件中获得相同的行为。

I also tried to pass the list as a parameter to my composable, but it didn't help at all.我还尝试将list作为参数传递给我的可组合项,但它根本没有帮助。

Try using a SnapshotStateList instead of an ordinary list as mutable state.尝试使用SnapshotStateList而不是普通列表作为可变 state。

So instead of this所以而不是这个

var myList: List<String> = mutableListOf()

try this,尝试这个,

var myList = mutableStateListOf("Item1")

and instead of using your ordinary list setting it with a new one every time you add an item, you can simply add new elements to a SnapshotStateList .而不是每次添加项目时都使用普通列表将其设置为新的列表,您只需将新元素添加到SnapshotStateList即可。

I modified your code and any changes coming from outside Greeting and inside of it reflects to LazyColumn我修改了您的代码,来自Greeting外部和内部的任何更改都会反映到LazyColumn

@Composable
fun Greeting(
     list: SnapshotStateList<String>
) {
    Button(onClick = {
        list.add("Item inside greeting")
    }) {
        Text(text = "Add")
    }

    LazyColumn(
        Modifier
            .fillMaxSize()
            .padding(16.dp)
    ) { ... }
}

Usage用法

setContent {
     Column {
          Button(onClick = {
                  myList.add("New Item Outside greeting")
          }) {}

          Greeting(myList)
     }
}

I've got a very good answer from @xy我从@xy那里得到了一个很好的答案

but then it lost value at recomposition.但随后它在重组时失去了价值。 Here is the updated code to handle my first problem while keeping the state of the list:这是更新后的代码,用于处理我的第一个问题,同时保留列表的 state:


var MainList: SnapshotStateList<String> = SnapshotStateList()

class MainActivity : ComponentActivity() {
    var myList: SnapshotStateList<String> = MainList

    @OptIn(ExperimentalComposeUiApi::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Theme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    Column(modifier = Modifier.fillMaxSize()) {
                        Greeting("Android", myList)
                    }
                }
            }
        }
    }
}

    @SuppressLint("RestrictedApi")
    override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
       MainList.add("$barcode")
    }
}

@OptIn(ExperimentalFoundationApi::class, ExperimentalComposeUiApi::class)
@Composable
fun Greeting(name: String, paramBarcode: String, theList: SnapshotStateList<ScanItem>) {
    var mutableList by remember { mutableStateOf(theList) }

    Column() {
        Button(onClick = {
            MainList.add("ABC0000000000001")
        }) {
            Text(text = "Add item")
        }
        Row() {
            Button(onClick = { 
            MainList.add("add00001")
            }) { 
                Text(text = "Add")
            }
            Button(
                onClick = { MainList.clear() }
            ) {
                Text("Empty list")
            }
        }
    }
}

And I can pass mutableList as the parameter in itemsIndexed, and it will keep the state on recompose.我可以将 mutableList 作为参数传递给 itemsIndexed,它会在重组时保留 state。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 发生异常后如何重新启动活动 - How to restart an activity after an exception has occured 如何在主要活动中从片段中触发事件? - How to fire event from fragment in main activity? 如何在 onClick 事件中调用可组合函数 - How to call a composable function in onClick event 销毁SurfaceView后如何返回主活动? - How To Return To The Main Activity After Destroying A SurfaceView? 登录后如何隐藏“主要活动”中的项目? - How to hide items on Main Activity after a Login? 删除另一个活动中的列表项后如何刷新主要活动? - How to refresh main activity after deleting a list item in another activity? 为什么当 state 在视图 model 中更改时,路由的 Composable 会重新组合? - Why does the Composable for the route recompose when state changes in the view model? 在关闭Android中的另一个活动后如何关闭主要活动? - how to close main activity after closing another activity in android? 如何在 Jetpack Compose 中从可组合导航到活动或片段? - How to navigate from a composable to an activity or a fragment in Jetpack Compose? 如何从另一个活动中获取活动中的变量并在从那里初始化后使主要活动使用变量?(kotlin) - how to get a variable in an activity from another activity and make the main activity to use variable after initializing from there ?(kotlin )
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM