【发布时间】:2021-09-29 10:43:37
【问题描述】:
我需要开发一个 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 popup。
我想撰写弹出窗口以显示在现有布局视图上。
如何做到这一点?
【问题讨论】:
标签: android popup android-jetpack-compose