How to create a Custom Dialog box in android?

2018-12-31 02:05发布

I want to create a custom dialog box like below

enter image description here

I have tried the following things.

  1. I created a subclass of AlertDialog.Builder and used a custom Title and Custom Content View and used that but the result was not as expected.

  2. Another attempt was to subclass DialogFragment and customize the dialog inside onCreateDialog that but result was not as expected.

  3. Then I tried using a plain Dialog class. The result was not as expected.

In all three cases, the problem is when I overlook the title view the size of the dialog is not as expected and when I use Title view the result is there is a thick border around the content view (which really looks bad). Now I have two questions in my mind...

  1. How can I achieve that? As I have already tried so many things, a direct answer will be more appreciated.

  2. What is the best way to show an error or alert dialog in an android app?

EDIT Android Developer Documentation recommends that we should use either DialogFragments or Dialogs for showing Error / Alert Messages to the user. However at one point they say ...

Tip: If you want a custom dialog, you can instead display an Activity as a dialog instead of using the Dialog APIs. Simply create an activity and set its theme to Theme.Holo.Dialog in the manifest element.

What is the meaning of that? Isn't it too much to use an Activity just for showing an error message???

15条回答
人气声优
2楼-- · 2018-12-31 02:16

Dialog Fragment is the simplest way of creating a custom Alert Dialog.Follow the above code to create a custom view for your dialog and then implement it using Dialog Fragment. Add the following code to your layout file:

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

See Custom Alert Dialog using Dialog Fragment to know how to do this.

查看更多
姐姐魅力值爆表
3楼-- · 2018-12-31 02:20

It's a class for Alert Dialog so that u can call the class from any activity to reuse the code.

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 file for the same is:

    <?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>
查看更多
后来的你喜欢了谁
4楼-- · 2018-12-31 02:21

I found this as the easiest way for showing custom dialog.

You have layout 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();
}
查看更多
余欢
5楼-- · 2018-12-31 02:27

Here I have created a simple Dialog, like:

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>

You have to extends Dialog and implements 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();
  }
}

How to Call Dialog ?

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

Updates

After a long time one of my friends asked me to make a curved shape dialog with a transparent background. So, Here I have implemented it.

enter image description here

To Make a curved shape you need to create a separate curve_shap.XML as below,

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

Now, add this curve_shap.XML in your main view Layout. In my case I have used 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>

How to call this ?

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

I hope that works for you.

查看更多
皆成旧梦
6楼-- · 2018-12-31 02:27

Create custom alert layout custom_aler_update.xml

then Copy to 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();

Coy to 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>
查看更多
永恒的永恒
7楼-- · 2018-12-31 02:28

Another easy way to do this.

step 1) create a layout with proper id's.

step 2) use the following code wherever you desire.

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();
查看更多
登录 后发表回答