我想创建一个自定义对话框如下

我尝试了以下几点。

我创建了AlertDialog的子类。生成器,并使用自定义标题和自定义内容视图,并使用,但结果不是预期的。 另一个尝试是子类DialogFragment和自定义对话框内的onCreateDialog,但结果不是预期的。 然后我尝试使用一个普通的Dialog类。结果并不如预期的那样。

在这三种情况下,问题是当我忽略标题视图时,对话框的大小不是预期的,当我使用标题视图时,结果是在内容视图周围有一个粗边框(这看起来真的很糟糕)。现在我脑子里有两个问题……

我怎样才能做到呢?因为我已经尝试了很多事情,直接的回答会更受欢迎。 在android应用程序中显示错误或警告对话框的最佳方式是什么?

编辑 Android开发者文档建议我们应该使用对话片段或对话框向用户显示错误/警报消息。然而,他们一度说……

提示:如果你想要一个自定义对话框,你可以将一个Activity显示为一个对话框,而不是使用对话框api。简单地创建一个活动,并将其主题设置为manifest元素中的theme . holo . dialog。

这是什么意思?仅仅是为了显示错误消息而使用Activity不是太过分了吗??


当前回答

这是一个示例对话框,使用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"

你可以做一个类扩展对话框,也像这样:

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();

    }
}

最后是call的形式,以你的活动为例:

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提供。

其他回答

创建这样的警告对话框布局

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:text="Custom Alert Dialog"
        android:layout_height="40dp">
    </Button>
</LinearLayout>

在Activity类上添加下面的代码

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LayoutInflater inflate = LayoutInflater.from(this);
    alertView = inflate.inflate(R.layout.your_alert_layout, null);
    Button btn= (Button) alertView.findViewById(R.id.btn);

    showDialog();
  }

 public void showDialog(){
        Dialog alertDialog = new Dialog(RecognizeConceptsActivity.this);
        alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        alertDialog.setContentView(alertView);
        alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        alertDialog.show();
    }

简单先创建一个类

 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();
        }
    }

然后创建custom_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>

然后在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>

round_button

<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)

你的结果,

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();

            }
        });

    }

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

Initialize and show dialog: ViewDialog alertDialoge = new ViewDialog(); alertDialoge.showDialog(getActivity(), "PUT DIALOG TITLE"); Create method: 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(); } } Create layout XML which you want or need.

另一种简单的方法。

步骤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();