Android 通过扩展 Dialog 或 AlertDialog 自定义对话框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1974887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Customizing dialog by extending Dialog or AlertDialog
提问by pengwang
I want to make a custom Dialog
. Because I don't like its style, I want to have rounded rectangle rather than sharp corners. I know how to implement it by theme in AndroidManifest.xml
, for example, I use:
我想定制一个Dialog
。因为我不喜欢它的风格,我想要圆角矩形而不是尖角。我知道如何通过主题实现它AndroidManifest.xml
,例如,我使用:
android:theme="@style/Theme.CustomDialog"
And Theme.CustomDialog.xml
:
并且Theme.CustomDialog.xml
:
<style name="Theme.CustomDialog" parent="android:style/Theme.Dialog">
<item name="android:windowBackground">@drawable/filled_box</item>
<item name="android:windowNoTitle">true</item>
filled_box.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#ffffffff"/>
<stroke android:width="3dp" color="#ffff8080"/>
<corners android:radius="30dp" />
<padding android:left="10dp" android:top="10dp"
android:right="10dp" android:bottom="10dp" />
</shape>
How can I implement a similar result by extending the Dialog
or AlertDialog
?
如何通过扩展Dialog
or来实现类似的结果AlertDialog
?
回答by Mark B
In the constructor of your class that extends Dialog call super(context, R.style.CustomDialog);
I've done this many times to create custom dialogs with specific themes.
在扩展 Dialog 调用的类的构造函数中,super(context, R.style.CustomDialog);
我已经多次这样做以创建具有特定主题的自定义对话框。
However if the theme is the only thing about the Dialog that you want to change, you could try just instantiating an instance of the Dialog class and pass it the theme ID like Dialog dialog = new Dialog(context, R.style.CustomDialog);
但是,如果主题是您想要更改的 Dialog 的唯一内容,则可以尝试仅实例化 Dialog 类的实例并将主题 ID 传递给它,例如 Dialog dialog = new Dialog(context, R.style.CustomDialog);
An example of extending Dialog:
扩展 Dialog 的示例:
public class MyDialog extends Dialog
{
public MyDialog(final Context context)
{
// Set your theme here
super(context, R.style.MyDialogTheme);
// This is the layout XML file that describes your Dialog layout
this.setContentView(R.layout.myDialogLayout);
}
}
The rest of the code you will add to this class is going to be pretty much exactly like what you would write in an Activity class.
您将添加到此类的其余代码将与您在 Activity 类中编写的代码非常相似。