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


350

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

在此处输入图片说明

我尝试了以下方法。

  1. 我创建了AlertDialog.Builder的子类,并使用了自定义的标题和自定义内容视图,并使用了它,但是结果与预期的不同。

  2. 另一个尝试是继承DialogFragment的子类并自定义onCreateDialog内的对话框,但结果不符合预期。

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

在这三种情况下,问题都是当我忽略标题视图时,对话框的大小与预期不符,而当我使用标题视图时,结果是在内容视图周围有一个粗边框(这看起来确实很糟糕)。现在我心中有两个问题...

  1. 我该如何实现?由于我已经尝试了很多事情,因此直接回答将更加感激。

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

EDIT Android开发人员文档建议我们应该使用DialogFragments或Dialogs向用户显示错误/警报消息。但是有一点他们说...

提示:如果需要自定义对话框,则可以将“活动”显示为对话框,而不是使用对话框API。只需创建一个活动并将其主题设置为清单元素中的Theme.Holo.Dialog。

那是什么意思?仅使用Activity来显示错误消息不是太多吗???


只是因为问题的第二部分却没有回答...什么是显示错误/提示信息给用户最好的方式..
艾米特

@ sumit-bijwani:我没有您需要的东西,已经接受了答案,您愿意为此提供赏金?
Akhil

3
使用DialogFragment比接受的答案好得多
Benoit

@Amit从图片上可以判断出您希望实现的对话框看起来像包含与标准AlertDialog相同的元素(标题,正文,按钮栏)。因此,我想您的外观可以仅通过样式来实现。
安徒生

为了实现这一点使用对话片段,看到learnzone.info/...
马达夫·巴特拉伊

Answers:


565

在这里,我创建了一个简单的对话框,例如:

对话框

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>

你必须extends Dialogimplements 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();  

更新

长时间后,我的一个朋友让我做一个透明背景的弧形对话框。因此,在这里我已经实现了它。

在此处输入图片说明

要制作弯曲形状,您需要创建以下单独的内容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 2014年

您可以直接调用intent,并且不要忘记在调用startActivity()之前先关闭dismiss()。尝试单击“是”,例如startActivity(new Intent(activity,new_activity.class));
Chintan Khetiya

3
@chintankhetiya,如果您想将数据从对话框传递到活动?我们将如何做?
Alvin 2014年

2
是什么R.id.TXT_Exit:
2015年

您要在其中调用对话框的视图。
Chintan Khetiya 2015年

186

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

希望它对您有用。


嗨,Alex,分享愉快!您可以与我们分享btn_flat_red_selector xml样式吗?谢谢
加斯顿Saillén

@GastónSaillén嗨,Gastón,我会搜索它,因为它很旧,我不记得该代码在哪里
Alex Zaraos

4
不要担心Alex,我已经制作了一个<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”安卓:topRightRadius = “7DP”/> </形状>(如果你愿意,你可以把它添加到您的答案)
加斯顿Saillén

94

另一个简单的方法。

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

34

在以下主题中添加 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 2014年

您可以使用@ErumHannanmdialog.findViewById(R.id.element);
Muhammed Refaat

25

简单先创建一个类

 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>

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

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

您的输出:)

在此处输入图片说明


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

            }
        });

    }

11

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

  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。


4

您可以尝试使用此简单的android对话框弹出库来减少混乱的对话框代码。在您的活动中使用非常简单。之后,您可以在活动中显示此代码以显示对话框

Pop.on(this).with().title(R.string.title).layout(R.layout.custom_pop).show();

其中R.layout.custom_pop是您想要装饰对话框的自定义布局。


4

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

你有布局 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();
}

4

创建自定义警报布局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:

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

3

更改背景颜色和文本样式的最简单方法是为android警报对话框创建自定义主题,如下所示:-

:只需将以下代码放入styles.xml中:

    <style name="AlertDialogCustom" parent="@android:style/Theme.Dialog">
    <item name="android:textColor">#999999</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowTitleStyle">@null</item>
    <item name="android:typeface">monospace</item>
    <item name="android:backgroundDimEnabled">false</item>
    <item name="android:textSize">@dimen/abc_text_size_medium_material</item>
    <item name="android:background">#80ff00ff</item>
</style>

:现在完成自定义操作,现在只需将其应用于您的alertBuilder对象:

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this,R.style.AlertDialogCustom);

希望这能够帮到你 !


3

Kotlin中的全屏自定义警报对话框类

  1. 创建XML文件,与执行活动一样

  2. 创建AlertDialog自定义类

    class Your_Class(context:Context) : AlertDialog(context){
    
     init {
      requestWindowFeature(Window.FEATURE_NO_TITLE)
      setCancelable(false)
     }
    
     override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.your_Layout)
      val window = this.window
      window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                         WindowManager.LayoutParams.MATCH_PARENT)
    
      //continue custom code here
      //call dismiss() to close
     }
    }
  3. 在活动中调用对话框

    val dialog = Your_Class(this)
    //can set some dialog options here
    dialog.show()

注意**:如果您不希望对话框全屏显示,请删除以下几行

      val window = this.window
      window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                         WindowManager.LayoutParams.MATCH_PARENT)

然后,将XML文件中顶部布局的layout_width和layout_height编辑为wrap_content或固定DP值。

我通常不建议使用固定DP,因为您可能希望您的应用程序适应多种屏幕尺寸,但是如果您将尺寸值保持足够小,则应该可以


2

创建警报对话框的布局是这样的

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

2

这是“警报对话框”的类,因此您可以从任何活动中调用该类以重用代码。

public class MessageOkFragmentDialog extends DialogFragment {
Typeface Lato;
String message = " ";
String title = " ";
int messageID = 0;

public MessageOkFragmentDialog(String message, String title) {
    this.message = message;
    this.title = title;
}


@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    LayoutInflater inflater = getActivity().getLayoutInflater();

    View convertview = inflater.inflate(R.layout.dialog_message_ok_box, null);


    Constants.overrideFonts(getActivity(), convertview);
    Lato = Typeface
            .createFromAsset(getActivity().getAssets(), "font/Lato-Regular.ttf");


    TextView textmessage = (TextView) convertview
            .findViewById(R.id.textView_dialog);

    TextView textview_dialog_title = (TextView) convertview.findViewById(R.id.textview_dialog_title);

    textmessage.setTypeface(Lato);
    textview_dialog_title.setTypeface(Lato);



    textmessage.setText(message);
    textview_dialog_title.setText(title);



    Button button_ok = (Button) convertview
            .findViewById(R.id.button_dialog);
    button_ok.setTypeface(Lato);

    builder.setView(convertview);
    button_ok.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            dismiss();

        }
    });


    return builder.create();

}
}

相同的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="match_parent"
    android:background="#ffffff"
    android:gravity="center_vertical|center"
    android:orientation="vertical">

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

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/blue_color"
            android:gravity="center_horizontal"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/textview_dialog_title"
                android:layout_width="wrap_content"
                android:layout_height="50dp"
                android:gravity="center"
                android:textColor="@color/white_color"
                android:textSize="@dimen/txtSize_Medium" />


        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/txt_white_color" />

        <TextView
            android:id="@+id/textView_dialog"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="@dimen/margin_20"
            android:textColor="@color/txt_gray_color"
            android:textSize="@dimen/txtSize_small" />

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="@color/txt_white_color"
            android:visibility="gone"/>

        <Button
            android:id="@+id/button_dialog"
            android:layout_width="wrap_content"
            android:layout_height="@dimen/margin_40"
            android:layout_gravity="center"
            android:background="@drawable/circular_blue_button"

            android:text="@string/ok"
            android:layout_marginTop="5dp"
            android:layout_marginBottom="@dimen/margin_10"
            android:textColor="@color/txt_white_color"
            android:textSize="@dimen/txtSize_small" />
    </LinearLayout>

</LinearLayout>

2

对话框片段是创建自定义警报对话框的最简单方法,请按照上述代码为您的对话框创建自定义视图,然后使用对话框片段来实现它。将以下代码添加到您的布局文件:

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

2

创建自定义警报对话框

cumstomDialog.xml

<ImageView
    android:id="@+id/icon"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_gravity="center"
    android:layout_margin="5dp"
    app:srcCompat="@drawable/error" />

<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:fontFamily="@font/muli_bold"
    android:text="Title"
    android:layout_marginTop="5dp"
    android:textColor="@android:color/black"
    android:textSize="15sp" />


<TextView
    android:id="@+id/description"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="10dp"
    android:fontFamily="@font/muli_regular"
    android:text="Message"
    android:textColor="@android:color/black"
    android:textSize="12dp" />

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="20dp"
    android:gravity="center"
    android:orientation="horizontal">

    <Button
        android:id="@+id/cancelBTN"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        android:layout_margin="5dp"
        android:background="@drawable/bground_radius_button_white"
        android:text="No"
        android:textColor="@color/black" />

    <Button
        android:id="@+id/acceptBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_margin="5dp"
        android:background="@drawable/bground_radius_button"
        android:text="Yes"
        android:textColor="@color/white" />
</LinearLayout>

在活动中显示自定义对话框:

  public void showDialog(String title, String des, int icon) {

    final Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.custom_dialog);
    dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

    Button cancelBTN = dialog.findViewById(R.id.cancelBTN);
    Button acceptBTN = dialog.findViewById(R.id.acceptBtn);
    TextView tvTitle = dialog.findViewById(R.id.title);
    TextView tvDescription = dialog.findViewById(R.id.description);
    ImageView ivIcon = dialog.findViewById(R.id.icon);

    tvTitle.setText(title);
    tvDescription.setText(des);
    ivIcon.setImageResource(icon);

    cancelBTN.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });

    acceptBTN.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

    dialog.show();
}

像这样打电话:

showDialog(“ Title”,“ Message”,R.drawable.warning);


1

我正在发布我正在使用的kotlin代码,它对我来说很好用。您还可以为对话框按钮设置点击监听器。

这是我的XML代码:

layout_custom_alert_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layoutDirection="ltr"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <View
        android:id="@+id/view6"
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:background="@color/colorPrimary" />

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/view6"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp">


        <TextView
            android:id="@+id/txt_alert_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            tools:text="are you sure?"
            android:textAlignment="center"
            android:textColor="@android:color/black"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />


        <Button
            android:id="@+id/btn_alert_positive"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/textView2"
            android:layout_marginTop="8dp"
            android:background="@android:color/transparent"
            tools:text="yes"
            android:textColor="@color/colorPrimaryDark"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toEndOf="@+id/btn_alert_negative"
            app:layout_constraintTop_toBottomOf="@+id/txt_alert_title" />

        <Button
            android:id="@+id/btn_alert_negative"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="8dp"
            android:background="@android:color/transparent"
            tools:text="no"
            android:textColor="@color/colorPrimaryDark"
            app:layout_constraintEnd_toStartOf="@+id/btn_alert_positive"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/txt_alert_title" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</RelativeLayout>

mAlertDialog.kt

class mAlertDialog(context: Context) {

    private val btn_positive : Button
    private val btn_negative : Button
    private val txt_alert_title : TextView
    private val dialog : AlertDialog
    init {
        val view = LayoutInflater.from(context).inflate(R.layout.layout_custom_alert_dialog,null)

        val dialog_builder = AlertDialog.Builder(context)
        dialog_builder.setView(view)

        btn_negative = view.findViewById(R.id.btn_alert_negative)
        btn_positive = view.findViewById(R.id.btn_alert_positive)
        txt_alert_title = view.findViewById(R.id.txt_alert_title)

        dialog = dialog_builder.create() 
    }

    fun show()
    {
        dialog.show()
    }

    fun setPositiveClickListener(listener :onClickListener)
    {
        btn_positive.setOnClickListener { v ->
            listener.onClick(btn_positive)
            dialog.dismiss()
        }
    }

    fun setNegativeClickListener(listener: onClickListener)
    {
        btn_negative.setOnClickListener { v ->
            listener.onClick(btn_negative)
            dialog.dismiss()
        }
    }

    fun setPoitiveButtonText(text : String)
    {
        btn_positive.text = text
    }


    fun setNegativeButtonText(text : String)
    {
        btn_negative.text = text
    }

    fun setAlertTitle(title : String)
    {
        txt_alert_title.text = title
    }
}

点击监听器的界面:

onClickListener.kt

interface onClickListener{
    fun onClick(view : View)
}

样品用量

val dialog = mAlertDialog(context)
                dialog.setNegativeButtonText("no i dont")
                dialog.setPoitiveButtonText("yes is do")
                dialog.setAlertTitle("do you like this alert dialog?")

                dialog.setPositiveClickListener(object : onClickListener {
                    override fun onClick(view: View) {
                        Toast.makeText(context, "yes", Toast.LENGTH_SHORT).show()
                    }
                })

                dialog.setNegativeClickListener(object : onClickListener {
                    override fun onClick(view: View) {
                        Toast.makeText(context, "no", Toast.LENGTH_SHORT).show()
                    }
                })

                dialog.show()

我希望这能帮到您!



1

以下是使用kotlin创建自定义视图对话框的代码。以下是对话框布局文件

<?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:orientation="vertical" android:layout_width="300dp"
    android:layout_height="400dp">

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />


</androidx.constraintlayout.widget.ConstraintLayout>

创建对话框并在文本视图中更新文本

val dialog = Dialog(activity!!)
dialog.setContentView(R.layout.my_dialog_layout)
dialog.tvTitle.text = "Hello World!!"
dialog.show()

1

这是创建自定义对话框的非常简单的方法。

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

1

导入自定义提醒:

LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.dse_location_list_filter, null);
final Dialog dialog = new Dialog(Acitvity_name.this);
dialog.setContentView(view);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
dialog.show();
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.