如何在安卓中创建自定义对话框?

406
我想创建一个类似下面的自定义对话框:

enter image description here

我尝试了以下几种方法:
  1. 创建了一个AlertDialog.Builder的子类,并使用自定义标题和自定义内容视图,但结果不如预期。

  2. 另一种尝试是创建DialogFragment的子类,并在onCreateDialog中自定义对话框,但结果不如预期。

  3. 然后我尝试使用普通的Dialog类。结果不如预期。

在这三种情况下,当我忽略标题视图时,对话框的大小不如预期,当我使用标题视图时,结果是内容视图周围有一个厚厚的边框(看起来真的很糟糕)。现在我脑海中有两个问题...
  1. 我该如何实现?由于我已经尝试了很多方法,直接回答将更加赞赏。

  2. 在Android应用程序中显示错误或警报对话框的最佳方法是什么?

编辑 Android开发文档建议我们使用DialogFragments或Dialogs来向用户显示错误/警报消息。然而在某一个点上,他们说...

提示:如果你想要一个自定义对话框,你可以代替使用Dialog APIs来显示一个Activity作为对话框。只需创建一个活动并将其主题设置为manifest元素中的Theme.Holo.Dialog即可。

这是什么意思?难道仅为了显示错误消息就使用一个Activity太过于浪费了吗?


仅因为问题的第二部分尚未回答...向用户显示错误/警报消息的最佳方法是什么? - Amit
@sumit-bijwani:我不明白你需要什么,已经有被接受的答案了,你为什么要提供悬赏? - Akhil
3
使用DialogFragment比接受的答案更好。 - Benoit
@Amit 根据图片来看,你想要实现的对话框似乎包含与标准 AlertDialog 相同的元素(标题、内容、按钮栏)。因此,我猜你可以仅通过样式来实现你想要的外观。 - Anderson
要使用Dialog Fragment实现此功能,请参见http://learnzone.info/android-tutorial-custom-alert-dialog-using-dialogfragment/。 - Madhav Bhattarai
21个回答

647

我创建了一个简单的对话框,如下图所示:

Dialog Box

custom_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="80dp"
    android:background="#3E80B4"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/txt_dia"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="10dp"
        android:text="Do you realy want to exit ?"
        android:textColor="@android:color/white"
        android:textSize="15dp"
        android:textStyle="bold"/>
    

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:background="#3E80B4"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/btn_yes"
            android:layout_width="100dp"
            android:layout_height="30dp"
            android:background="@android:color/white"
            android:clickable="true"
            android:text="Yes"
            android:textColor="#5DBCD2"
            android:textStyle="bold" />

        <Button
            android:id="@+id/btn_no"
            android:layout_width="100dp"
            android:layout_height="30dp"
            android:layout_marginLeft="5dp"
            android:background="@android:color/white"
            android:clickable="true"
            android:text="No"
            android:textColor="#5DBCD2"
            android:textStyle="bold" />
    </LinearLayout>

</LinearLayout>

您需要扩展对话框(Dialog)实现OnClickListener接口

public class CustomDialogClass extends Dialog implements
    android.view.View.OnClickListener {

  public Activity c;
  public Dialog d;
  public Button yes, no;

  public CustomDialogClass(Activity a) {
    super(a);
    // TODO Auto-generated constructor stub
    this.c = a;
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.custom_dialog);
    yes = (Button) findViewById(R.id.btn_yes);
    no = (Button) findViewById(R.id.btn_no);
    yes.setOnClickListener(this);
    no.setOnClickListener(this);

  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btn_yes:
      c.finish();
      break;
    case R.id.btn_no:
      dismiss();
      break;
    default:
      break;
    }
    dismiss();
  }
}

如何调用对话框?

R.id.TXT_Exit:
CustomDialogClass cdd=new CustomDialogClass(Values.this);
cdd.show();  

更新

长时间之后,我的一个朋友要求我制作一个带有透明背景的弧形对话框。因此,我已经实现了它。

enter image description here

为了制作一个弧形,你需要创建一个单独的curve_shap.XML文件,如下所示:

<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <solid android:color="#000000" />

    <stroke
        android:width="2dp"
        android:color="#ffffff" />

    <corners
        android:bottomLeftRadius="20dp"
        android:bottomRightRadius="20dp"
        android:topLeftRadius="20dp"
        android:topRightRadius="20dp" />

</shape>

现在,在您的主视图布局中添加此curve_shap.XML。在我的例子中,我使用了LinearLayout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="80dp"
        android:background="@drawable/curve_shap"
        android:orientation="vertical" >
...
</LinearLayout>

如何称呼这个?

CustomDialogClass cdd = new CustomDialogClass(MainActivity.this);
cdd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
cdd.show();

我希望那对你有效。


1
这段代码适用于我的应用程序。我只想问一下,当点击对话框按钮时,如何跳转到另一个活动? - Manwal
4
如果你想从对话框传递数据到活动中,应该怎么做? - Alvin
3
R.id.TXT_Exit是什么? - Jack
你想要调用对话框的视图。 - Chintan Khetiya
@Alvin:你可以使用接口监听器将数据从对话框传递到活动。 - Anand Savjani
显示剩余9条评论

220

这是一个使用XML创建的对话框示例。

输入图像描述

下面的XML代码仅为示例,设计或视图在此处实现:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffffff">

<ImageView
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:id="@+id/a"
    android:gravity="center"
    android:background="#DA5F6A"
    android:src="@drawable/dialog_cross"
    android:scaleType="fitCenter" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TEXTO"
    android:id="@+id/text_dialog"
    android:layout_below="@+id/a"
    android:layout_marginTop="20dp"
    android:layout_marginLeft="4dp"
    android:layout_marginRight="4dp"
    android:layout_marginBottom="20dp"
    android:textSize="18sp"
    android:textColor="#ff000000"
    android:layout_centerHorizontal="true"
    android:gravity="center_horizontal" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="30dp"
    android:text="OK"
    android:id="@+id/btn_dialog"
    android:gravity="center_vertical|center_horizontal"
    android:layout_below="@+id/text_dialog"
    android:layout_marginBottom="20dp"
    android:background="@drawable/btn_flat_red_selector"
    android:layout_centerHorizontal="true"
    android:textColor="#ffffffff" />

</RelativeLayout>

这些代码行是drawable资源:

android:src="@drawable/dialog_cross"
android:background="@drawable/btn_flat_red_selector"

你可以使用类继承Dialog,也可以像这样:

public class ViewDialog {

    public void showDialog(Activity activity, String msg){
        final Dialog dialog = new Dialog(activity);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCancelable(false);
        dialog.setContentView(R.layout.dialog);

        TextView text = (TextView) dialog.findViewById(R.id.text_dialog);
        text.setText(msg);

        Button dialogButton = (Button) dialog.findViewById(R.id.btn_dialog);
        dialogButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.show();

    }
}

最后是调用的形式,以您的Activity为例:

ViewDialog alert = new ViewDialog();
alert.showDialog(getActivity(), "Error de conexión al servidor");

我希望它能对你有用。

更新

用于对话框的可绘制XML:

<shape xmlns:android="schemas.android.com/apk/res/android"> <stroke android:width="2dp" android:color="#FFFFFF" /> <gradient android:angle="180" android:endColor="@color/NaranjaOTTAA" android:startColor="@color/FondoActionBar" /> <corners android:bottomLeftRadius="7dp" android:bottomRightRadius="7dp" android:topLeftRadius="7dp" android:topRightRadius="7dp" /> </shape> 

这个 XML 是由 @GastónSaillén 提供的。


嗨,Alex,分享得不错!!你能和我们分享btn_flat_red_selector xml样式吗?谢谢。 - Gastón Saillén
@GastónSaillén 你好,Gastón,我会去搜索一下,因为这是旧代码,我不记得它在哪里了。 - Alex Zaraos
6
不用担心,Alex,我已经制作好了一个。 <shape xmlns:android="http://schemas.android.com/apk/res/android"> <stroke android:width="2dp" android:color="#FFFFFF" /> <gradient android:angle="180" android:endColor="@color/NaranjaOTTAA" android:startColor="@color/FondoActionBar" /> <corners android:bottomLeftRadius="7dp" android:bottomRightRadius="7dp" android:topLeftRadius="7dp" android:topRightRadius="7dp" /> </shape>(如果您想的话,可以将其添加到您的答案中) - Gastón Saillén
你只需要上下文来创建一个对话框,所以即使传递活动也可以工作,但你不应该通过将其变成必需品来增加范围。 - Haroon

115

另一种简单的方法。

步骤1)创建具有适当ID的布局。

步骤2)在您需要的任何位置使用以下代码。

LayoutInflater factory = LayoutInflater.from(this);
final View deleteDialogView = factory.inflate(R.layout.mylayout, null);
final AlertDialog deleteDialog = new AlertDialog.Builder(this).create();
deleteDialog.setView(deleteDialogView);
deleteDialogView.findViewById(R.id.yes).setOnClickListener(new OnClickListener() {    
    @Override
    public void onClick(View v) {
        //your business logic 
        deleteDialog.dismiss();
    }
});
deleteDialogView.findViewById(R.id.no).setOnClickListener(new OnClickListener() {    
    @Override
    public void onClick(View v) {
        deleteDialog.dismiss();    
    }
});

deleteDialog.show();

47

首先创建一个简单的类

 public class ViewDialog {

        public void showDialog(Activity activity, String msg){
            final Dialog dialog = new Dialog(activity);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(false);
            dialog.setContentView(R.layout.custom_dialogbox_otp);
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

            TextView text = (TextView) dialog.findViewById(R.id.txt_file_path);
            text.setText(msg);

            Button dialogBtn_cancel = (Button) dialog.findViewById(R.id.btn_cancel);
            dialogBtn_cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    Toast.makeText(getApplicationContext(),"Cancel" ,Toast.LENGTH_SHORT).show();
                    dialog.dismiss();
                }
            });

            Button dialogBtn_okay = (Button) dialog.findViewById(R.id.btn_okay);
            dialogBtn_okay.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    Toast.makeText(getApplicationContext(),"Okay" ,Toast.LENGTH_SHORT).show();
                    dialog.cancel();
                }
            });

            dialog.show();
        }
    }

然后创建一个自定义的_dialogbox_otp

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="330dp"
    android:layout_height="160dp"
    android:background="#00555555"
    android:orientation="vertical"
    android:padding="5dp"
    android:weightSum="100">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/round_layout_otp"
        android:orientation="vertical"
        android:padding="7dp"
        android:weightSum="100">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="60"
            android:orientation="horizontal"
            android:weightSum="100">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="80"
                android:gravity="center">

                <ImageView
                    android:id="@+id/a"
                    android:layout_width="50dp"
                    android:layout_height="50dp"
                    android:background="#DA5F6A"
                    android:gravity="center"
                    android:scaleType="fitCenter"
                    android:src="@mipmap/infoonetwo" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="20">

                <TextView
                    android:id="@+id/txt_file_path"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:singleLine="true"
                    android:text="TEXTO"
                    android:textColor="#FFFFFF"
                    android:textSize="17sp"
                    android:textStyle="bold" />
            </LinearLayout>
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="40"
            android:background="@drawable/round_layout_white_otp"
            android:orientation="vertical"
            android:weightSum="100">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_gravity="center"
                android:layout_weight="60">

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:gravity="center"
                    android:text="Do you wanna Exit..?"
                    android:textColor="#ff000000"
                    android:textSize="15dp"
                    android:textStyle="bold" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="40"
                android:orientation="horizontal"
                android:weightSum="100">


                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginRight="30dp"
                    android:layout_weight="50"
                    android:gravity="center|right">

                    <Button
                        android:id="@+id/btn_cancel"
                        android:layout_width="80dp"
                        android:layout_height="25dp"
                        android:background="@drawable/round_button"
                        android:gravity="center"
                        android:text="CANCEL"
                        android:textSize="13dp"
                        android:textStyle="bold"
                        android:textColor="#ffffffff" />

                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginLeft="30dp"
                    android:layout_weight="50"
                    android:gravity="center|left">


                    <Button
                        android:id="@+id/btn_okay"
                        android:layout_width="80dp"
                        android:layout_height="25dp"
                        android:background="@drawable/round_button"
                        android:text="OKAY"
                        android:textSize="13dp"
                        android:textStyle="bold"
                        android:textColor="#ffffffff" />

                </LinearLayout>
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

在drawable文件夹下创建以下xml文件,针对round_layout_white_otp.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <!-- <corners android:radius="10dp" /> -->
    <corners
        android:bottomLeftRadius="18dp"
        android:bottomRightRadius="16dp"
        android:topLeftRadius="38dp"
        android:topRightRadius="36dp" />
    <solid android:color="#C0C0C0" />
    </shape>

对于round_layout_otp.xml文件

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <!-- <corners android:radius="10dp" /> -->
    <corners
        android:bottomLeftRadius="18dp"
        android:bottomRightRadius="16dp"
        android:topLeftRadius="38dp"
        android:topRightRadius="38dp" />
    <solid android:color="#DA5F6A" />
    </shape>

圆形按钮

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <!-- <corners android:radius="10dp" /> -->
    <corners
        android:bottomLeftRadius="7dp"
        android:bottomRightRadius="7dp"
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp" />
    <solid android:color="#06A19E" />
    </shape>

最后使用下面的代码来可视化您的对话框 :)

ViewDialog alert = new ViewDialog();
        alert.showDialog(ReceivingOTPRegActivity.this, "OTP has been sent to your Mail ");

你的输出 :)

输入图片描述

答案已更新 : 用于Kotlin

  class ViewDialog {
        fun showResetPasswordDialog(activity: Activity?) {
            val dialog = Dialog(activity!!)
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
            dialog.setCancelable(false)
            dialog.setContentView(R.layout.resetpass_popup)
            dialog.window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
            val dialogBtn_remove = dialog.findViewById<TextView>(R.id.txtClose)
            dialogBtn_remove.setOnClickListener {
                dialog.dismiss()
                activity!!.finish()
            }
            dialog.show()
        }
    }

以及你的XML设计,

<?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:ignore="MissingDefaultResource">

    <androidx.cardview.widget.CardView
        android:layout_width="340dp"
        android:layout_height="290dp"
        android:layout_marginLeft="12dp"
        android:layout_marginRight="12dp"
        app:cardCornerRadius="11dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <ImageView
                android:layout_width="61dp"
                android:layout_height="61dp"
                android:layout_gravity="center"
                android:layout_marginTop="12dp"
                android:src="@drawable/tickmark"
                tools:ignore="ContentDescription"></ImageView>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="22dp"
                android:layout_marginTop="18dp"
                android:layout_marginRight="12dp"
                android:fontFamily="@font/opensans_semibold"
                android:text="@string/apasswordreset"
                android:textColor="@color/gender_txt"
                android:textSize="15dp"
                tools:ignore="HardcodedText,RtlHardcoded,SpUsage"></TextView>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="22dp"
                android:layout_marginRight="12dp"
                android:fontFamily="@font/opensans_semibold"
                android:text="@string/toyourmail"
                android:textColor="@color/gender_txt"
                android:textSize="15dp"
                tools:ignore="HardcodedText,RtlHardcoded,SpUsage">


            </TextView>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="22dp"
                android:layout_marginTop="18dp"
                android:layout_marginRight="12dp"
                android:fontFamily="@font/opensans_regular"
                android:text="@string/followthe"
                android:textColor="@color/gender_txt"
                android:textSize="14dp"
                tools:ignore="HardcodedText,RtlHardcoded,SpUsage"></TextView>

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="22dp"
                android:layout_marginRight="12dp"
                android:fontFamily="@font/opensans_regular"
                android:text="@string/inyouremail"
                android:textColor="@color/gender_txt"
                android:textSize="14dp"
                tools:ignore="HardcodedText,RtlHardcoded,SpUsage"></TextView>


            <TextView
                android:id="@+id/txtClose"
                android:layout_width="150dp"
                android:layout_height="40dp"
                android:layout_gravity="center"
                android:layout_marginTop="38dp"
                android:background="@drawable/nextbtn"
                android:fontFamily="@font/opensans_semibold"
                android:gravity="center"
                android:text="Close"
                android:textColor="@color/white_o"
                android:textSize="16dp"
                tools:ignore="HardcodedText,RtlHardcoded,SpUsage"></TextView>

        </LinearLayout>

    </androidx.cardview.widget.CardView>
</androidx.constraintlayout.widget.ConstraintLayout>

现在,您可以调用

val alert = ViewDialog()
alert.showResetPasswordDialog(activity)

而你的结果,

enter image description here


38
将以下主题添加到values->style.xml中。
<style name="Theme_Dialog" parent="android:Theme.Light">
     <item name="android:windowNoTitle">true</item>
     <item name="android:windowBackground">@android:color/transparent</item>
</style>

像这样在你的onCreateDialog方法中使用这个主题:

Dialog dialog = new Dialog(FlightBookActivity.this,R.style.Theme_Dialog);

在xml文件中定义对话框布局,包括标题栏,并像这样设置该xml文件:

dialog.setContentView(R.layout.your_dialog_layout);

这对我来说看起来是最好的解决方案(它使用了最少的代码)。你为什么选择了 Chintan Khetiya 的答案?它比这个更好在哪里? - wojciii
1
Vinnet Shukla 如何在 R.layout.your_dialog_layout 上应用点击事件,以便我可以使用自定义布局并对其进行操作。 - Erum
@ErumHannan 你可以使用 mdialog.findViewById(R.id.element); - Muhammed Refaat

15
public static void showCustomAlertDialog(Context context, String name,
            String id, String desc, String fromDate, String toDate,
            String resions) {
        final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                context);
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.dialog, null);
        alertDialogBuilder.setView(view);
        alertDialogBuilder.setCancelable(false);
        final AlertDialog dialog = alertDialogBuilder.create();
        dialog.show();
        txt_empId = (TextView) view.findViewById(R.id.txt_dialog_empcode);
        txt_empName = (TextView) view.findViewById(R.id.txt_dialog_empname);
        txt_desc = (TextView) view.findViewById(R.id.txt_dialog_desc);
        txt_startDate = (TextView) view.findViewById(R.id.txt_dialog_startDate);
        txt_resions = (TextView) view.findViewById(R.id.txt_dialog_endDate);
        txt_empId.setTypeface(Utils.setLightTypeface(context));
        txt_empName.setTypeface(Utils.setLightTypeface(context));
        txt_desc.setTypeface(Utils.setLightTypeface(context));
        txt_startDate.setTypeface(Utils.setLightTypeface(context));
        txt_resions.setTypeface(Utils.setLightTypeface(context));

        txt_empId.setText(id);
        txt_empName.setText(name);

        txt_desc.setText(desc);
        txt_startDate.setText(fromDate + "\t to \t" + toDate);
        txt_resions.setText(resions);



        btn_accept = (Button) view.findViewById(R.id.btn_dialog_accept);
        btn_reject = (Button) view.findViewById(R.id.btn_dialog_reject);
        btn_cancel = (Button) view.findViewById(R.id.btn_dialog_cancel);
        btn_accept.setTypeface(Utils.setBoldTypeface(context));
        btn_reject.setTypeface(Utils.setBoldTypeface(context));
        btn_cancel.setTypeface(Utils.setBoldTypeface(context));

        btn_cancel.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dialog.dismiss();

            }
        });

    }

12

创建自定义对话框的最简单方法:

  1. 初始化并显示对话框:

     ViewDialog alertDialoge = new ViewDialog();
     alertDialoge.showDialog(getActivity(), "PUT DIALOG TITLE");
    
  2. 创建方法:

    public class ViewDialog {
    
      public void showDialog(Activity activity, String msg) {
    
        final Dialog dialog = new Dialog(activity);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCancelable(false);
        dialog.setContentView(R.layout.custom_dialoge_feedback);
    
        TextView text = (TextView) dialog.findViewById(R.id.text_dialog_feedback);
        text.setText(msg);
    
        Button okButton = (Button) dialog.findViewById(R.id.btn_dialog_feedback);
        Button cancleButton = (Button) dialog.findViewById(R.id.btn_dialog_cancle_feedback);
        final EditText edittext_tv = (EditText) dialog.findViewById(R.id.dialoge_alert_text_feedback);
    
        okButton.setOnClickListener(new View.OnClickListener() {
    
            @Override
            public void onClick(View v) {
                //Perfome Action
            }
        });
        cancleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
    
        dialog.show();
    
        }
    }
    
  3. 创建你想要或需要的布局XML。


6

我发现这是展示自定义对话框的最简单方法。

您有一个名为your_layout.xml的布局文件。

public void showCustomDialog(final Context context) {
    Dialog dialog = new Dialog(context);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = inflater.inflate(R.layout.your_layout, null, false);
    findByIds(view);  /*HERE YOU CAN FIND YOU IDS AND SET TEXTS OR BUTTONS*/
    ((Activity) context).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
    dialog.setContentView(view);
    final Window window = dialog.getWindow();
    window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
    window.setBackgroundDrawableResource(R.color.colorTransparent);
    window.setGravity(Gravity.CENTER);
    dialog.show();
}

6

下面是一个非常简单的创建自定义对话框的方法。

dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<!--  Put your layout content  -->
</LinearLayout>

MainActivity.java

ShowPopup(){
LayoutInflater li = LayoutInflater.from(this);
View promptsView = li.inflate(R.layout.dialog, null);
android.app.AlertDialog.Builder alertDialogBuilder = new 
android.app.AlertDialog.Builder(this);
alertDialogBuilder.setView(promptsView);
alertDialogBuilder.setCancelable(true);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}

5

创建自定义警报布局custom_aler_update.xml

然后将此代码复制到Activity中:

AlertDialog basic_reg;
AlertDialog.Builder builder ;
builder = new AlertDialog.Builder(ct, R.style.AppCompatAlertDialogStyle);
LayoutInflater inflater = ((Activity) ct).getLayoutInflater();
View v = inflater.inflate(R.layout.custom_aler_update, null);
builder.setView(v);
builder.setCancelable(false);
builder.create();
basic_reg = builder.show();

将此代码复制到样式中:

复制此代码以应用样式:

<style name="AppCompatAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:textColorPrimary">@color/primaryTextColor</item>
    <item name="android:background">@color/white</item>
</style>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接