[英]How to migrate my custom view to Jetpack Compose?
我有一個以傳統方式創建的自定義視圖:從View類繼承。
具體來說,我的自定義視圖有許多可以在 XML 布局中分配的自定義屬性(及其相應的 Kotlin 屬性):
<com.example.MyCustomView
app:myCustomAttr1 = "..."
app:myCustomAttr2 = "..."/>
除了使用AndroidView類在 Jetpack Compose 中加載傳統的 Android 視圖之外,如何將我的視圖轉換為“真正的”Compose 組件?
我應該為自定義視圖的每個部分提供單獨的可組合項嗎? 例如,一個可組合的餅圖,另一個可組合的圖例框?
Android 開發者文檔沒有提到如何將自定義視圖轉換為 Compose。
假設我已經創建了這樣的視圖的可組合版本:
@Composable fun MyComposable(title: String) {
Text(title)
}
要像常規View一樣使用該可組合組件(能夠在 XML 中指定其屬性),我們應該從AbstractComposeView創建一個自定義視圖子類:
// 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)
}
}
這就是我們將如何使用它,就像 XML 中的常規視圖一樣:
<my.package.name.MyCustomView
android:id="@+id/myView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:myAttribute="Helloooooooooo!" />
和/或在活動中:
val myCustomView = findViewById<MyCustomView>(R.id.myView)
myCustomView.myProperty = "Woohoo!"
感謝 ProAndroidDev 提供這篇文章。
要為您的視圖定義您自己的自定義屬性,請參閱這篇文章。
此外,請確保使用AndroidX Core庫的-ktx版本,以便能夠訪問有用的 Kotlin 擴展函數,例如Context::withStyledAttributes
:
implementation("androidx.core:core-ktx:1.6.0")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.