Android AlertDialog with rounded corners
Asked Answered
L

8

38

I have been trying to make my Alert Dialog with rounded corners but somehow I am not able to. I have tried and I failed. I tried to follow this blog http://blog.stylingandroid.com/archives/271 and made my styles based on that.

Btw, to add to my question now. Some of my new finding. The code in the above link just works fine on 2.3.3 (GB) but does not work at all in ICS . Some change made the code to break.

I want to avoid creating 9 patch images and thus I am using shapes. 9 patch image is the last thing that I will try.I know that android alert dialog style is using 9 patch image. I already looked that up before throwing this question.

/res/values/themes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="MyTheme" parent="@android:style/Theme.Dialog">
        <item name="android:alertDialogStyle">@style/dialog</item>
    </style>


</resources>

/res/values/styles.xml

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

    <style name="AppTheme" parent="android:Theme.Light" />

    <style name="myImageView">

        <!-- 3dp so the background border to be visible -->
        <item name="android:padding">3dp</item>
        <item name="android:background">@drawable/image_drawable</item>
        <item name="android:scaleType">fitCenter</item>
    </style>

    <style name="dialog">
        <item name="android:fullDark">@drawable/dialog_body</item>
        <item name="android:topDark">@drawable/dialog_title</item>
        <item name="android:centerDark">@drawable/dialog_body</item>
        <item name="android:bottomDark">@drawable/dialog_footer</item>
        <item name="android:fullBright">@drawable/dialog_body</item>
        <item name="android:centerBright">@drawable/dialog_body</item>
        <item name="android:topBright">@drawable/dialog_title</item>
        <item name="android:bottomBright">@drawable/dialog_footer</item>
        <item name="android:bottomMedium">@drawable/dialog_footer</item>
        <item name="android:centerMedium">@drawable/dialog_body</item>
    </style>

</resources>

/res/drawable/dialog_title.xml

<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetBottom="-1dp">
    <shape android:shape="rectangle">
        <solid android:color="#FFFFFF" />
        <corners android:topLeftRadius="5dp" android:topRightRadius="5dp" />
        <stroke android:color="#FFFFFF" android:width="1dp" />
    </shape>
</inset>

/res/drawable/dialog_body.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient android:startColor="#FFFFFFFF" android:endColor="#FFFFFFFF"
        android:angle="270" />
</shape>

/res/drawable/dialog_footer.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

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

    <corners
        android:bottomLeftRadius="5dp"
        android:bottomRightRadius="5dp" />

    <stroke
        android:width="1dp"
        android:color="#FFFFFF" />

</shape>

res/layout/dialog_layout.xml

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="45dp"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/button1"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="90dp"
        android:layout_toLeftOf="@+id/textView1"
        android:background="@drawable/button_selector"
        android:text="Ok"
        android:textColor="@android:color/white"
        android:textStyle="bold" />

    <Button
        android:id="@+id/button2"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/button1"
        android:layout_marginRight="48dp"
        android:background="@drawable/button_selector"
        android:text="More"
        android:textColor="@android:color/white"
        android:textStyle="bold" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/button1"
        android:layout_marginTop="41dp"
        android:orientation="vertical" >
    </LinearLayout>

</RelativeLayout>

My code for AlertDialog:

public static void createYesNoDialog(final Context context, String positivebuttonname,
            String negativebuttonname, String message, int messagedrawable, String headermessage,
            final DialogResponse dr) {
        final DialogResponse dialogResponse = dr;
        ContextThemeWrapper ctw = new ContextThemeWrapper(context,
                com.gp4ever.worldlogo.quiz.R.style.MyTheme);

        AlertDialog.Builder builder = new AlertDialog.Builder(ctw);
        LayoutInflater inflater = (LayoutInflater)context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout = inflater.inflate(com.gp4ever.worldlogo.quiz.R.layout.dialog_layout, null);
        TextView text = (TextView)layout.findViewById(com.gp4ever.worldlogo.quiz.R.id.textView1);
        Button buttonOk = (Button)layout.findViewById(com.gp4ever.worldlogo.quiz.R.id.button1);
        Button buttonMore = (Button)layout.findViewById(com.gp4ever.worldlogo.quiz.R.id.button2);
        text.setText(message);
        if (messagedrawable > 0) {
            text.setCompoundDrawablesWithIntrinsicBounds(messagedrawable, 0, 0, 0);
        } else if (messagedrawable == 0)
            text.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
        builder.setView(layout);
        builder.setCancelable(false);
        builder.setTitle(headermessage);
        builder.setIcon(android.R.drawable.ic_dialog_alert);
        final AlertDialog dialog = builder.create();

        buttonOk.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dialog.cancel();
            }
        });
        buttonMore.setOnClickListener(new OnClickListener() {

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

}

My current output:

I do not get any rounded corners. I can see that it is different from the usual style. Even though I change radius on my drawable, the corners does not reflect to those changes.

enter image description here

Lammas answered 19/9, 2012 at 19:22 Comment(3)
Can you not use a 9 patch image as the background that has rounded corners?Montherlant
No, I want to avoid creating 9 patch images and instead use shapes. 9 patch image the last thing that I will try. Let me clarify that in my question as well.Lammas
I know that android alert dialog style is using 9 patch image. I already looked that up before throwing this question.Lammas
J
39

You can do it using the following code:

CustomDialog.java:

public class MainActivity extends Activity{

    private static final int ALERT_DIALOG = 1;

    @Override
    public void onCreate( Bundle savedInstanceState )
    {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.main );

        ( (Button) findViewById( R.id.button1 ) )
            .setOnClickListener( new OnClickListener()
                {
                    public void onClick( View v )
                    {
                        showDialog( ALERT_DIALOG );
                    }
                }
            );
    }

    @Override
    protected Dialog onCreateDialog( int id ){
        Dialog dialog = null;
        if ( id == ALERT_DIALOG )
        {
            ContextThemeWrapper ctw = new ContextThemeWrapper( this, R.style.MyTheme );
            AlertDialog.Builder builder = new AlertDialog.Builder( ctw );
            builder.setMessage( "Hello World" )
                .setTitle( "Alert Dialog" )
                .setIcon( android.R.drawable.ic_dialog_alert )
                .setCancelable( false )
                .setPositiveButton( "Close", new DialogInterface.OnClickListener()
                    {
                        public void onClick( DialogInterface dialog, int which )
                           {
                                dialog.dismiss();
                           }
                        } 
                    );
            dialog = builder.create();
        }
        if ( dialog == null )
        {
            dialog = super.onCreateDialog( id );
        }
        return dialog;
     }
 }

dialog_title.xml

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android" android:insetBottom="-1dp">
    <shape android:shape="rectangle">
        <solid android:color="#000000" />
        <corners android:topLeftRadius="20dp" android:topRightRadius="20dp" />
        <stroke android:color="#7F7F7F" android:width="1dp" />
    </shape>
</inset>

dialog_footer.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#7F7F7F" />
    <corners android:bottomLeftRadius="20dp" android:bottomRightRadius="20dp" />
    <stroke android:color="#7F7F7F" android:width="1dp" />
</shape>

Just change the radius amount in:

dialog_title.xml

and

dialog_footer.xml

and that'll generate the following output:

enter image description here

hope this will help you.


UPDATE:
I'm not an expert but this is what I found. It may be right or wrong. After many attempts I ended up with the following:

1- ContextThemeWrapper is not applicable for API 14, it works fine on Gingerbread and older versions but with API > 10 it doesn't work.

2- to overcome the above issue and make it work on API > 10 as requested, I replace this line:

ContextThemeWrapper ctw = new ContextThemeWrapper( this, R.style.MyTheme );
AlertDialog.Builder builder= new AlertDialog.Builder( ctw );

with this:

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

but you need to change:

android:minSdkVersion="8"  

to

android:minSdkVersion="11" 

the result will be as shown in the following image on ICS (API 14):

enter image description here

This image is from a Samsung Galaxy S3 running ICS.

Note: modified project initiated with API 14 SO manifest sdk will be:

<uses-sdk
  android:minSdkVersion="11"
  android:targetSdkVersion="15" />

FINAL WORD: As my little knowledge in Android development (I'm not an expert),

1- custom alert dialog runs smoothly in API < 10 but not > 10 with the same Java code,

if we want it to run in ICS with the same effect as appeared in API < 10, we need to modify the code, so it will run on ICS but will not run in any version down API 11.

2- even the result in ICS is not satisfactory, the round corner applies only to the title but not the footer.


SECOND UPDATE: FINALLY I get all corners round,

JUST apply padding to dialog_footer.xml as follows:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
    <solid android:color="#7F7F7F" />
    <corners android:bottomLeftRadius="20dp" android:bottomRightRadius="20dp" />
    <stroke android:color="#7F7F7F" android:width="1dp" />
    <padding android:left="10dp" android:top="10dp" android:right="10dp"
android:bottom="10dp" /> 
</shape>

Output image:

enter image description here

This image is from a Samsung Galaxy S3 running ICS.

Janijania answered 23/9, 2012 at 8:55 Comment(16)
I know I can do this with dialog, I would like to do it with AlertDialog though. I am trying to create alertdialog with my theme. I do not want any other customization. I just want rounded corners. If you look at the blog link that I have posted, that code did work some day but now it is not working. I don't know what is wrong with it now.Lammas
@Lammas i tried the sample code from above link and run it on my mobile , its already rounded corner .Janijania
@Lammas i applied your theme i get it round tooJanijania
Can you try to change the roundness and see if it is getting changed. I don't see that changing at all.Lammas
I already know that I need to change the radius the in my drawable shapes in order to get more roundedness. I already tried changing those radius. It didn't work for me.Lammas
Btw, to add to my question now. Some of my new finding. The code in the link just works fine on 2.3.3 (GB) but does not work at all in ICS . Some change made the code to break.Lammas
I am trying exactly the same code as given from link and just changed radius to 15dp. The code works well if I run on 2.3.3 (GB) device but does not work on ICS. Did you try to run the code on ICS?Lammas
@Lammas im out side now when reach home i will run it on ICS devise and replay youJanijania
No issues. Thanks for your time.Lammas
@Lammas i test it on ICS device , its not only did not show the round corner but also did not apply the whole theme , im working on that issue , any finding i will tell youJanijania
Yes, I am aware that it did not apply the whole theme. Thanks, I am working on that too. Let's see whats wrong.Lammas
Thanks for the finidings. I will try it out and let you know but I think you deserve the bounty.Lammas
@Lammas THANKS ALOT MY FRIEND im still work on it please if you reach to full solution please tell me , also if i find any solution i will tell you , dont forget to add style and theme to folder ( values-v14), thanksJanijania
Thanks. I will keep you posted.Lammas
Cool, so it works as expected. Thanks for spending your valuable time on it. I really really appreciate it.Lammas
@Lammas YOU ARE ALWAYS WELCOME .Janijania
I
22

Just one more step from @iDroid Explorer answer

add this line when you build the dialog

dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

and this will get the rectangle disappear (which actually is transparent) and get a perfect rounded dialog box.

Interracial answered 23/1, 2014 at 9:48 Comment(2)
Nice! Edit a little bit because of syntax error: dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));Trochal
Just set the dialog background to the rounded drawable rather than the view, and you don't need two calls.Misadventure
B
15

Just use the MaterialAlertDialogBuilder included in the official Material Components library.

new MaterialAlertDialogBuilder(MainActivity.this,R.style.MyThemeOverlay_MaterialComponents_MaterialAlertDialog)
            .setTitle("Dialog")
            .setMessage("Lorem ipsum dolor ....")
            .setPositiveButton("Ok", /* listener = */ null)
            .setNegativeButton("Cancel", /* listener = */ null)
            .show();

Then define the style using the shapeAppearanceOverlay attribute.

 <style name="MyThemeOverlay.MaterialComponents.MaterialAlertDialog" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
    <item name="shapeAppearanceOverlay">@style/ShapeAppearanceOverlay.MyApp.Dialog.Rounded</item>
  </style>

  <style name="ShapeAppearanceOverlay.MyApp.Dialog.Rounded" parent="">
    <item name="cornerFamily">rounded</item>
    <item name="cornerSize">8dp</item>
  </style>

enter image description here

Bridle answered 8/9, 2019 at 16:57 Comment(2)
Very Nicely explained .Thanks sirBarbital
Nice and simple solution! However, I had to add '<item name="colorSurface">@color/<your resource></item>' to "MyThemeOverlay.MaterialComponents.MaterialAlertDialog" otherwise my app would crash.Pasturage
E
5

I have try the same problem with below one and it works for me. Even for ICS also.

1. First i have put the theme to my AlertDialog.

final Dialog  nag = new Dialog(this,android.R.style.Theme_Translucent_NoTitleBar_Fullscreen);
        nag.requestWindowFeature(Window.FEATURE_NO_TITLE);
        nag.setCancelable(true);
        nag.setContentView(R.layout.pop_exit);  
        Button btnNO = (Button)nag.findViewById(R.id.btn_popup_NO);
        Button btnYES = (Button)nag.findViewById(R.id.btn_popup_YES);


        btnNO.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

            nag.cancel();


            }
        });

        btnYES.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                System.exit(0);

            }
        });

        nag.show();

2. Then have implemented the Custom Layout for the Dialog view

pop_exit.xml

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

    <!-- <LinearLayout android:orientation="vertical" android:layout_marginLeft="20dp" 
        android:layout_marginRight="20dp" android:background="#95000056" android:layout_width="fill_parent" 
        android:layout_height="wrap_content"> -->

    <LinearLayout android:orientation="vertical"
        android:layout_marginLeft="20dp" android:layout_marginRight="20dp"
        android:background="@drawable/round" android:layout_width="fill_parent"
        android:layout_height="wrap_content">



        <TextView android:text="Exit Application"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal" android:textStyle="bold"
            android:textColor="#fff" android:textSize="20dp"
            android:layout_marginTop="5dp" />


        <LinearLayout android:layout_width="fill_parent"
            android:layout_height="wrap_content" android:orientation="horizontal"
            android:layout_marginTop="5dp" android:weightSum="2"
            android:layout_marginLeft="10dp" android:layout_marginRight="10dp"
            android:gravity="center">

            <Button android:text="No" android:layout_weight="1"
                android:gravity="center" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:id="@+id/btn_popup_NO" />

            <Button android:text="Ok" android:layout_weight="1"
                android:layout_width="wrap_content" android:layout_height="wrap_content"
                android:id="@+id/btn_popup_YES" />
        </LinearLayout>


    </LinearLayout>

</LinearLayout>

3. Now add shape to the Background of parent layout of pop_exit.xml

round.xml // shape file

    <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#99000056" />
    <corners android:radius="35px" />
    <padding android:left="0dp" android:top="0dp" android:right="0dp"
        android:bottom="0dp" />
</shape>

I just do it. It will works for you also for ICS.

Hope it will help you. If not then let me know.

Enjoy Coding...

:)

Ervinervine answered 28/9, 2012 at 5:30 Comment(2)
Thanks for taking time to answer. If you look at the comments above and revision history of answer by android116. He answered pretty much the same what your saying. I am again replying the same to you, that I am aware that I can acomplish rounded corners by this means but what I am using is AlertDialog.Builder. The code that I have written is fine for GB but for ICS it does not work. I want to know the reason for that.Lammas
its working fine but its give rounded rectangle outside of the alert box.which means it gives outlayer as rounded rectangle and inner layer with rectangle please help me.I want only one rounded rectangle layerNor
G
5

Most Simplest Way:

dialog_card.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@android:color/white"/>
    <corners android:radius="8dp"/>
</shape>

themes.xml

<!--    ... your other style codes -->

<style name="MyAlertTheme" parent="@style/Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:windowBackground">@drawable/dialog_card</item>
</style>

In your Activity

AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this, R.style.MyAlertTheme);
alert.setTitle("<Your Title>");
alert.setMessage("<Your Message>");
// ...

Bonus:

If you want to use this AlertDialog everywhere in your app,
just add <item name="alertDialogTheme">@style/MyAlertTheme</item> in your AppTheme.

So you don't have to pass R.style.MyAlertTheme in the second parameter of AlertDialog.BUilder.

themes.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
<!-- here -->
    <item name="alertDialogTheme">@style/MyAlertTheme</item>
</style>
Galenical answered 7/3, 2021 at 4:6 Comment(1)
I had to use android:background instead of android:windowBackground.Protrusion
M
4

As you state you dont want to use a 9 patch image, take a look here.

https://mcmap.net/q/121532/-how-do-i-create-a-listview-with-rounded-corners-in-android

The principle is exactly the same, except you assign the background to your layout where this example is to a linear layout.

Montherlant answered 21/9, 2012 at 20:59 Comment(3)
I did try to do that but then I have my Dialog layout which has rounded corners and then the outer rectangle which is a part of the dialog theme by default in android. So think of a rounded layout inside of rectangle, that is what I get.Lammas
Drop the alert dialog for a custom one maybe.Montherlant
That is not the problem. I know I can do this easily if I go for dialog activity and other options. But I want to make sure that I can change the AlertDialog style the way I want.Lammas
M
3
  1. create xml in drawable folder with dialog_corner.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
  <solid android:color="@color/main_background"/>
  <corners
    android:topLeftRadius="@dimen/margin_10" 
    android:topRightRadius="@dimen/margin_10"
    android:bottomRightRadius="@dimen/margin_10" 
    android:bottomLeftRadius="@dimen/margin_10" />
</shape>

2.put in layout

android:background="@drawable/dialog_corner"

3.in you java file keep below code

View mView = LayoutInflater.from(mContext).inflate(R.layout.layout_pob,null); 
alertDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
Mansell answered 11/11, 2016 at 11:51 Comment(0)
K
0

this works for me:

<style name="AppTheme.AlertDialog" parent="Theme.AppCompat.Light.Dialog.Alert">
        <item name="android:colorBackground">@android:color/transparent</item>
        <item name="android:background">@drawable/dialog_bg</item>
</style>

dialog_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/white"/>
    <corners android:radius="12dp"/>
</shape>
Kwapong answered 21/12, 2021 at 17:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.