Android:Activity 中的 Jetpack Compose 和 XML

问题描述 投票:0回答:5

如何在同一活动中添加 Jetpack Compose 和 xml?一个例子就完美了。

android kotlin android-jetpack-compose android-custom-view compose-multiplatform
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!")
    }
  }
}

如果您想要相反的效果,即在撰写中使用 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
  }
)

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。为此,您的项目必须启用视图绑定。 AndroidView 与许多其他内置可组合项一样,采用 Modifier 参数,例如,可以使用该参数设置其在父可组合项中的位置。

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

2
投票

更新:当您想在撰写功能中使用 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元素 通过将其添加到布局文件中,您可以将其与数据绑定一起使用,也可以通过 findviewbyId 在您的活动/片段中使用它,并在 setContent 方法中定义您的撰写 UI。有关更详细的示例,您可以查看这篇文章 https://medium.com/p/51662a94c552

© www.soinside.com 2019 - 2024. All rights reserved.