在我的 Android 应用程序中,“关于”屏幕设置为对话框,如下所述:
class AboutDialog : DialogFragment() {
// ...
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = inflater.inflate(R.layout.about_dialog, container, false).apply {
findViewById<ComposeView>(R.id.about_view).apply {
setViewCompositionStrategy(DisposeOnViewTreeLifecycleDestroyed)
setContent {
AboutScreen()
}
isClickable = true
}
}
}
...
about_dialog.xml
:
<?xml version="1.0" encoding="utf-8"?>
<androidx.compose.ui.platform.ComposeView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/about_view"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
...
AboutScreen
可组合项:
@Composable
fun AboutScreen {
MyTheme {
Scaffold { contentPadding ->
Box(
Modifier
.padding(contentPadding)
.fillMaxSize()
.verticalScroll(rememberScrollState())
) {
Column {
// ...
}
}
}
}
}
对话框(屏幕截图中的模糊部分)扩展到屏幕的一定百分比,以便背景屏幕在左侧和右侧可见。
如何配置对话框的宽度?
您可以使用以下。
class AboutDialog : DialogFragment() {
// ...
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = inflater.inflate(R.layout.about_dialog, container, false).apply {
//Sets the dialog width to targetWidth
(dialog as ComponentDialog).apply {
setOnShowListener {
val targetWidth = 400
window!!.attributes = window!!.attributes.apply {
width = targetWidth
}
}
}
//rest of your codes
}
}
编辑: 或者您可以为对话框设置自定义主题。这甚至会在显示对话框之前设置宽度。
//You need to extend AppCompatDialogFragment instead of DialogFragment
//to make the custom AppCompat theme work
class AboutDialog : AppCompatDialogFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
//Apply custom theme
setStyle(STYLE_NORMAL, R.style.Theme_CustomDialog)
super.onCreate(savedInstanceState)
}
//rest of your codes
}
res/values/styles.xml
<resources>
<style name="Theme.CustomDialog" parent="@style/ThemeOverlay.AppCompat.Dialog">
<!--Portrait-->
<item name="windowFixedWidthMinor">50%</item>
<item name="windowFixedHeightMinor">50%</item>
<item name="android:windowMinWidthMinor">50%</item>
<!--Landscape-->
<item name="windowFixedWidthMajor">50%</item>
<item name="windowFixedHeightMajor">50%</item>
<item name="android:windowMinWidthMajor">50%</item>
</style>
</resources>