如何在android中更改alertdialog框样式

时间:2016-01-01 01:17:39

标签: android android-alertdialog

我只是想为我的Android应用程序构建一个alertdialog。

我真正想要的是一个像这样的对话框: enter image description here

其正面和负面按钮填充在对话框

但我总是这样:

enter image description here

并且这两个按钮在对话框的右上角粘在一起

任何人都可以告诉我如何将alertdialog从第二个更改为第一个?

非常感谢

2 个答案:

答案 0 :(得分:1)

为此你需要创建自定义dilogbox像这样 Dialog xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<ImageView
    android:id="@+id/image"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:contentDescription="@drawable/ic_launcher"
    android:src="@drawable/ic_launcher" />

<Button
    android:id="@+id/button"
    android:layout_width="100dp"
    android:layout_height="wrap_content"
    android:layout_below="@+id/image"
    android:layout_centerHorizontal="true"
    android:text="Dismiss" />

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_above="@+id/button"
    android:layout_toRightOf="@+id/image"
    android:gravity="center_vertical"
    android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

在你的活动中:

final Dialog dialog = new Dialog(MainActivity.this);

            //setting custom layout to dialog
            dialog.setContentView(R.layout.cusotm_dialog_layout);
            dialog.setTitle("Custom Dialog");

            //adding text dynamically
            TextView txt = (TextView) dialog.findViewById(R.id.textView);
            txt.setText("Put your dialog text here.");

            ImageView image = (ImageView)dialog.findViewById(R.id.image);
            image.setImageDrawable(getResources().getDrawable(android.R.drawable.ic_dialog_info));

            //adding button click event
            Button dismissButton = (Button) dialog.findViewById(R.id.button);
            dismissButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });
            dialog.show();

答案 1 :(得分:0)

您可以使用setView(view)方法将自定义布局设置为警告对话框,如下所示:

 AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
 LayoutInflater inflater = this.getLayoutInflater();
 View dialogView = inflater.inflate(R.layout.alert_layout, null);
 dialogBuilder.setView(dialogView);
 AlertDialog alertDialog = dialogBuilder.create();
 alertDialog.show();