使用View Binding
项目中启用 view binding
android {
buildFeatures {
viewBinding = true // 启用 视图绑定 view binding 针对布局xml
}
}
dependencies {
implementation("androidx.compose.ui:ui")
implementation("androidx.compose.ui:ui-viewbinding")
}
导入xml布局文件,文件名会对应生成绑定类(规则为按照下划线分配大小写)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="<http://schemas.android.com/apk/res/android>"
xmlns:app="<http://schemas.android.com/apk/res-auto>"
xmlns:tools="<http://schemas.android.com/tools>"
按照id给绑定类增加函数
android:id="@+id/layout_sign_in_api"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<com.huawei.hms.support.hwid.ui.HuaweiIdAuthButton
每个id对应一个xml块,也对应一个绑定类的函数。
android:id = "@+id/layout_sign_in_api_xml"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:hwid_button_theme="hwid_button_theme_full_title"
app:hwid_color_policy="hwid_color_policy_red"
app:hwid_corner_radius="hwid_corner_radius_large"
/>
</LinearLayout>
组件调用
@Composable
private fun SignInScreen(
mContext : Context,
onClick : ()->Unit,
) {
// val binding = LayoutSignInApiBinding.inflate
AndroidViewBinding(
factory=LayoutSignInApiBinding::inflate,
update ={
this.layoutSignInApiXml.setOnClickListener {
onClick()
}
},
onReset={},
onRelese = {}
)
// AndroidView(
// modifier = Modifier
// .fillMaxWidth(),
// factory={conten
// LayoutInflater.from(mContext).inflate(
// R.layout.layout_sign_in_api, null, false
// )
//
// }
// )
//
// DisposableEffect(view) {
// val onClickListener = View.OnClickListener {
// Log.d(TAG,"ONcLICK")
// onClick()
//// Toast.makeText(mContext, "View clicked", Toast.LENGTH_SHORT).show()
// }
//
// view.setOnClickListener(onClickListener)
//
// onDispose {
// // 在此处处理资源清理
// view.setOnClickListener(null)
// }
// }
}
参考: