[英]Android overlay window using jetpack compose
我需要开发一个 android 库,它应该能够允许使用我的库的开发人员在其当前屏幕上显示一个覆盖窗口。 我可以为此使用弹出覆盖,但覆盖 UI 应该是声明性的。 我正在尝试使用 Jetpack compose 为叠加创建声明性 UI。 我在 kotlin 文件中创建了一个简单的弹出窗口,如下所示
class MyView {
@Composable
fun pop() {
Box {
val popupWidth = 200.dp
val popupHeight = 50.dp
val cornerSize = 16.dp
Popup(alignment = Alignment.Center) {
// Draw a rectangle shape with rounded corners inside the popup
Box(
Modifier
.size(popupWidth, popupHeight)
.background(Color.White, RoundedCornerShape(cornerSize))
)
}
}
}
}
为了测试这一点,我创建了一个带有如下按钮的活动
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
@ExperimentalMaterialApi
fun showComposeView(view: android.view.View)
{
setContent {
MyView().pop()
}
}
}
上述活动的布局文件如下,
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="21dp"
android:text="Button"
android:onClick="showComposeView"
app:layout_constraintStart_toStartOf="@+id/textView"
app:layout_constraintTop_toBottomOf="@+id/textView" />
</androidx.constraintlayout.widget.ConstraintLayout>
现在,问题是,当我单击按钮时,上述布局文件中的视图将被 compose 弹出窗口替换。
我想编写弹出窗口以显示在现有布局视图上。
如何实现这一目标?
调用setContent{}
就像调用setContentView
,您替换Activity
的根View
。
您要做的是混合Compose
和常规View
,您最好的选择可能是将您的布局放在AndroidView
Composable 中。 你可以在这里找到更多信息
@Composable
fun MyPopupContainer(@LayoutRes layout: Int) {
var showPopup by remember { mutableStateOf(false) }
AndroidView(factory = { context ->
// Inflate your view the way you want, using layout inflater or ViewBinding
val view = LayoutInflater.from(context).inflate(layout, null)
view.findViewById<View>(R.id.button).setOnClickListener {
showPopup = true
}
// returning the view we just created
view
})
// When showPopup is false, your popup won't be displayed
if (showPopup) {
// Your popup function here
MyView().pop()
}
}
然后在你的Activity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent { MyPopupContainer(R.layout.your_xml_layout) }
}
我可以使用底部工作表对话框片段在现有布局上显示组合弹出窗口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.