Android:Jetpack Compose和Activity中的XML

49

我该如何在同一个活动中添加Jetpack Compose和xml?最好附上示例。

5个回答

112

如果你想在XML文件中使用Compose,你可以将以下代码添加到你的布局文件中:

<androidx.compose.ui.platform.ComposeView
  android:id="@+id/my_composable"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content" />

然后,设置内容:

findViewById<ComposeView>(R.id.my_composable).setContent {
  MaterialTheme {
    Surface {
      Text(text = "Hello!")
    }
  }
}

如果您想要相反的操作,即在Compose中使用XML文件,则可以使用以下代码:

AndroidView(
  factory = { context ->
    val view = LayoutInflater.from(context).inflate(R.layout.my_layout, null, false)
    val textView = view.findViewById<TextView>(R.id.text)

    // do whatever you want...
    view // return the view
  },
  update = { view ->
    // Update the view
  }
)

1
感谢您的解释,真的节省了时间。 - Sattar
1
谢谢你的非常友善和准确的回答。 - Bruno Sosa Fast Tag

18

如果您想像普通的View一样提供可组合性(具有在XML中指定其属性的能力),请从AbstractComposeView进行子类化。

@Composable 
fun MyComposable(title: String) {
    Text(title)
}
// Do not forget these two imports for the delegation (by) to work
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue

class MyCustomView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0
) : AbstractComposeView(context, attrs, defStyle) {

    var myProperty by mutableStateOf("A string")

    init {
        // See the footnote
        context.withStyledAttributes(attrs, R.styleable.MyStyleable) {
            myProperty = getString(R.styleable.MyStyleable_myAttribute)
        }
    }

    // The important part
    @Composable override fun Content() {
        MyComposable(title = myProperty)
    }
}

这就是您如何像使用常规视图一样使用它:

<my.package.name.MyCustomView
    android:id="@+id/myView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:myAttribute="Helloooooooooo!" />

感谢ProAndroidDev提供这篇文章

注脚

如果您想为您的视图定义自己的自定义属性,请参见此帖子
此外,请确保使用AndroidX Core库的-ktx版本,以便能够访问有用的Kotlin扩展函数,例如Context::withStyledAttributes

implementation("androidx.core:core-ktx:1.6.0")

12

https://developer.android.com/jetpack/compose/interop?hl=en

要嵌入 XML 布局,使用由 androidx.compose.ui:ui-viewbinding 库提供的 AndroidViewBinding API。为此,您的项目必须启用 view binding。 与许多其他内置组合项一样,AndroidView 接受 Modifier 参数,例如可用于设置其在父组合项中的位置。

@Composable
fun AndroidViewBindingExample() {
    AndroidViewBinding(ExampleLayoutBinding::inflate) {
        exampleView.setBackgroundColor(Color.GRAY)
    }
}

2
更新:当您想在compose函数中使用XML文件时
AndroidView(
  factory = { context ->
    val view = LayoutInflater.from(context).inflate(R.layout.test_layout, null, false)
    val edittext= view.findViewById<EditText>(R.id.edittext)

    view 
  },
  update = {  }
)

0
你可以使用xml元素<androidx.compose.ui.platform.ComposeView />,并通过将其添加到布局文件中,可以使用数据绑定或通过findviewbyId在活动/片段中使用它,并在setContent方法中定义你的Compose UI。有关更详细的示例,你可以查看这篇文章https://medium.com/p/51662a94c552

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接