Ver*_*una -3 android kotlin android-jetpack android-jetpack-compose
Mah*_*zad 19
如果您想像常规View一样提供可组合项(能够在 XML 中指定其属性),请从AbstractComposeView进行子类化。
@Composable
fun MyComposable(title: String) {
Text(title)
}
Run Code Online (Sandbox Code Playgroud)
// 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)
}
}
Run Code Online (Sandbox Code Playgroud)
这就是你如何像普通视图一样使用它:
<my.package.name.MyCustomView
android:id="@+id/myView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:myAttribute="Helloooooooooo!" />
Run Code Online (Sandbox Code Playgroud)
感谢 ProAndroidDev 撰写本文。
要为您的视图定义您自己的自定义属性,请参阅这篇文章。
另外,请确保使用AndroidX Core库的-ktx版本,以便能够访问有用的 Kotlin 扩展函数,例如:Context::withStyledAttributes
implementation("androidx.core:core-ktx:1.6.0")
Run Code Online (Sandbox Code Playgroud)
小智 12
https://developer.android.com/jetpack/compose/interop?hl=en
要嵌入 XML 布局,请使用库提供的AndroidViewBinding
androidx.compose.ui:ui-viewbinding
API 。为此,您的项目必须启用视图绑定。AndroidView 与许多其他内置可组合项一样,采用 Modifier 参数,该参数可用于设置其在父可组合项中的位置等。
@Composable
fun AndroidViewBindingExample() {
AndroidViewBinding(ExampleLayoutBinding::inflate) {
exampleView.setBackgroundColor(Color.GRAY)
}
}
Run Code Online (Sandbox Code Playgroud)
如果要在 XML 文件中使用 Compose,可以将其添加到布局文件中:
<androidx.compose.ui.platform.ComposeView
android:id="@+id/my_composable"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Run Code Online (Sandbox Code Playgroud)
然后,设置内容:
findViewById<ComposeView>(R.id.my_composable).setContent {
MaterialTheme {
Surface {
Text(text = "Hello!")
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果你想要相反的,在你的撰写中使用一个 XML 文件,你可以使用这个:
AndroidView(
viewBlock = { context: 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 viw
},
update = { view ->
// Update view
}
)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1823 次 |
最近记录: |