我正试图实现以下布局
我尝试使用Row(Modifier.weight(50f))
,这是编译器开始抛出
如果从ColumnInstance
- import androidx.compose.foundation.layout.ColumnScopeInstance.weight
导入
Cannot access 'ColumnScopeInstance': it is internal in 'androidx.compose.foundation.layout'
如果从RowInstance
- androidx.compose.foundation.layout.RowScopeInstance.weight
导入
Cannot access 'RowScopeInstance': it is internal in 'androidx.compose.foundation.layout'
在下面附加我的可组合代码
@Composable
fun BoxLayout(){
Row(Modifier.weight(50f)) {
BoxWithText()
BoxWithText()
}
}
附加整个文件以供参考
package me.sanjaykapilesh.layoutmastery
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScopeInstance.weight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import me.sanjaykapilesh.layoutmastery.ui.theme.LayoutMasteryTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
LayoutMasteryTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
BoxWithText()
}
}
}
}
}
@Composable
fun BoxLayout(){
Row(Modifier.weight(50f)) {
BoxWithText()
BoxWithText()
}
}
@Composable
fun BoxWithText() {
Column() {
Text(text = "Hello Box!")
Text(text = "Displays text and follows Material Design guidelines")
}
}
@Preview(showBackground = true)
@Composable
fun BoxLayoutPreview() {
LayoutMasteryTheme {
BoxLayout()
}
}
我不知道为什么我会出错。我也无法实现Modifier.weight
发布于 2022-10-09 05:00:47
有些修饰符是它们定义的作用域所特有的,比如Modifier.weight在默认情况下仅在RowScope或ColumnScope中可用。或者Modifier.align只能在BoxScope中使用。
当您希望访问这些修饰符时,您需要在这些作用域中包含可组合函数,或者创建一个带有这些作用域接收方的@Composable参数的函数
@Composable
fun BoxLayout(){
Row(Modifier.weight(50f)) {
BoxWithText()
BoxWithText()
}
}
BoxLayout应该返回RowScope/ColumnScope,以便能够使用Modifier.weight,这可以作为
@Composable
fun BoxWithLayout(content: @Composable RowScope.()->Unit){
Row {
content()
}
}
@Composable
private fun Sample() {
BoxWithLayout {
Row(Modifier.weight(50f)) {
BoxWithText()
BoxWithText()
}
}
}
发布于 2022-10-28 19:39:59
您可以使用扩展函数来获取上下文。例如:
@Composable
fun ColumnScope.BoxLayout(){
Row(Modifier.weight(50f)) {
BoxWithText()
BoxWithText()
}
}
https://stackoverflow.com/questions/74001640
复制相似问题