Android alertdialog rounded corners

Android AlertDialog with rounded corners

Posted by: admin February 23, 2018 Leave a comment

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

/res/values/styles.xml

/res/drawable/dialog_title.xml

/res/drawable/dialog_body.xml

/res/drawable/dialog_footer.xml

res/layout/dialog_layout.xml

My code for AlertDialog:

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.

You can do it using the following code:

Just change the radius amount in:

and that’ll generate the following output:

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:

but you need to change:

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

This image is from a Samsung Galaxy S3 running ICS.

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

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

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

if we want it to run in ICS with the same effect as appeared in API

SECOND UPDATE:
FINALLY I get all corners round,

JUST apply padding to dialog_footer.xml as follows:

This image is from a Samsung Galaxy S3 running ICS.

Just one more step from @iDroid Explorer answer

add this line when you build the dialog

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

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.

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

pop_exit.xml

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

round.xml // shape file

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

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

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

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

Читайте также:  Второй рабочий стол андроид самсунг

create xml in drawable folder with 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));

android – How do I display a CalendarView in an AlertDialog?

Questions: I’m trying to display the CalendarView in an Alert Dialog, but all that shows up is the month/year and the days of the week. These are the contents of the layout file:

How do I convert a PSD design to Android xml?

Questions: Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers. Want to improve this question? Update the question so it’s on-topic for Stack Over.

Источник

Android AlertDialog with rounded corners

You can do it using the following code:

Just change the radius amount in:

and that’ll generate the following output:

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:

but you need to change:

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

This image is from a Samsung Galaxy S3 running ICS.

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

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

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

if we want it to run in ICS with the same effect as appeared in API

SECOND UPDATE: FINALLY I get all corners round,

JUST apply padding to dialog_footer.xml as follows:

This image is from a Samsung Galaxy S3 running ICS.

Just one more step from @iDroid Explorer answer

add this line when you build the dialog

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

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

Then define the style using the shapeAppearanceOverlay attribute.

Источник

Android AlertDialog с закругленными углами

Я пытаюсь сделать свой диалог оповещений с закругленными углами, но как-то не могу. Я пробовал, и я потерпел неудачу. Я попытался следить за этим блогом http://blog.stylingandroid.com/archives/271 и сделал мои стили на основе этого.

Кстати, чтобы добавить к моему вопросу сейчас. Некоторые из моих новых находок. Код в приведенной выше ссылке просто отлично работает на 2.3.3 (GB), но не работает вообще в ICS. Некоторые изменения заставили код сломаться.

Я хочу избежать создания 9 патч-изображений, и поэтому я использую фигуры. 9 патч-изображение – последнее, что я попробую. Я знаю, что стиль диалога предупреждения Android использует 9 патч-изображений. Я уже посмотрел, прежде чем задавать этот вопрос.

/res/values/themes.xml

/res/values/styles.xml

/res/drawable/dialog_title.xml

/res/drawable/dialog_body.xml

/res/drawable/dialog_footer.xml

разреш / макет / dialog_layout.xml

Мой код для AlertDialog:

Мой текущий выход:

У меня нет закругленных углов. Я вижу, что он отличается от обычного стиля. Несмотря на то, что я меняю радиус на мой рисунок, углы не отражают этих изменений.

Вы можете сделать это, используя следующий код:

Просто измените размер радиуса в:

И это будет генерировать следующий результат:

Читайте также:  Темы ссср для андроида

Надеюсь, что это поможет вам.

ОБНОВИТЬ:
Я не эксперт, но это то, что я нашел. Это может быть правильно или неправильно. После многих попыток я получил следующее:

1- ContextThemeWrapper не применим для API 14, он отлично работает на Gingerbread и более старых версиях, но с API> 10 он не работает.

2- чтобы преодолеть вышеупомянутую проблему и заставить ее работать с API> 10 по запросу, я заменю эту строку:

Но вам нужно изменить:

Результат будет показан на следующем рисунке на ICS (API 14):

Это изображение от Samsung Galaxy S3, работающего под управлением ICS.

Примечание: измененный проект, инициированный с помощью API 14 SO manifest sdk, будет:

ЗАКЛЮЧИТЕЛЬНОЕ СЛОВО: Как мои маленькие знания в разработке Android (я не эксперт),

1- пользовательское диалоговое окно предупреждений выполняется плавно в API 10 с тем же кодом Java,

Если мы хотим, чтобы он работал в ICS с тем же эффектом, что и в API

2- даже результат в ICS не является удовлетворительным, круглый угол применяется только к названию, но не к нижнему колонтитулу.

ВТОРОЕ ОБНОВЛЕНИЕ: НАКОНЕЦ Я получаю все углы вокруг,

dialog_footer.xml padding к dialog_footer.xml следующим образом:

Это изображение от Samsung Galaxy S3, работающего под управлением ICS.

Еще один шаг от ответа @iDroid Explorer

Добавьте эту строку при построении диалога

И это приведет к исчезновению прямоугольника (что на самом деле является прозрачным) и получить идеальное закругленное диалоговое окно.

Я постараюсь решить одну и ту же проблему ниже, и она работает для меня. Даже для ICS.

1. Сначала я поставил тему в свой AlertDialog.

2. Затем были реализованы пользовательские макеты для просмотра диалогового окна

pop_exit.xml

3. Теперь добавьте форму в фон родительского макета pop_exit.xml

Файл round.xml // shape

Я просто делаю это. Он будет работать и для вас, и для ICS .

Надеюсь, это поможет вам. Если нет, то дайте мне знать.

Как вы заявляете, вы не хотите использовать 9 патч-изображений, посмотрите здесь.

Принцип точно такой же, за исключением того, что вы назначаете фон вашему макету, где этот пример относится к линейной компоновке.

Создайте xml в выпадающей папке с помощью dialog_corner.

Источник

Android Custom Dialog With Animation

Hello and welcome to another tutorial from Codingdemos, today you will learn how to create an Android custom dialog, this dialog will have animation, background color, ImageView and Button. You can use this Alertdialog as an indicator when something good or bad occur while the user uses your app.

By the end of this tutorial, you will have an app that looks like this. (Large preview)

In this tutorial we will be using the following:

    – Android studio version 3.2.1
    – Android emulator Nexus 5X with API 26
    – Minimum SDK API 16

Create new Android Studio project or open existing project. (Large preview)

2- Open colors.xml file to change the colors of the main app.

Changing app appearance

3- Build and run the app to see the new colors.

4- Open activity_main.xml file, here you need to add 2 Android Buttons. These 2 buttons will be placed on the same line in the center of the screen.

5- Create a new xml layout file and name it dialog_postive_layout, you will use this as the layout for Positive Dialog.

Create layout resource file in Android Studio. (Large preview)

6- Create an icon that you will use it for Android ImageView.

Create vector asset in Android Studio. (Large preview)

Choose icon inside Android studio asset studio. (Large preview)

7- Add the following code inside dialog_postive_layout.xml file.

Читайте также:  Андроид с наушниками airpods

In this layout you’ve added an Android ImageView which will show the icon that you’ve create it using Android asset studio, 2 Android Textviews that will show the title and a message and finally an Android Button that you will use it later to dismiss Android dialog box.

8- Here is how the layout looks like in Android Studio preview tab.

9- I’m sure you’ve noticed that you literally can’t see the text, let’s fix it by giving a green background color for the layout.

Here is how Android custom dialog look like. (Large preview)

10- Here is the full code for dialog_postive_layout.xml file.

11- Create a new Android layout resource file and name it dialog_negative_layout.

12- Add the following code inside dialog_negative_layout.xml file.

Here is how Android custom dialog look like. (Large preview)

13- Here is the full code for dialog_negative_layout.xml file.

14- Open MainActivity.java file, here is where you will reference those 2 Android Buttons as well as creating Alertdialog box.

15- Now you need to work on setting up Android dialog, since you have 2 custom alertdialog, instead of writing duplicate code you will create a function that will handle this work.

As you can see the function name is showAlertDialog that takes an int value which is the custom alertdialog layout ID. Inside this function you will setup alertdialog.

16- Next you need to make those 2 Buttons clickable by calling setOnClickListener and then you will call showAlertDialog function to show custom alertdialog on the user’s screen.

17- Build and run the app to see the output.

Here is Android Custom Alertdialog. (Large preview)

Android custom dialog with rounded corners

It’s good to finally see that custom alertdialog, it will be really cool if you can have rounded corners around alertdialog! Let’s do it now 🙂

18- Create a new Android drawable resource file, name it dialog_positive_round and add in the following code.

Here you use shape as the root layout, then you give it a color, set the radius and finally give it some padding around it.

19- Open dialog_postive_layout.xml and change the background value of the root layout.

20- Repeat the same steps (18 & 19) to have rounded corners for dialog_negative_layout.xml.

21- Build and run the app to see the result.

Android custom dialog positive status. (Large preview)

Android custom dialog negative status. (Large preview)

22- One thing you will notice is there is a white background at the corners of the dialog box. You can fix it by adding the following code inside showAlertDialog function.

23- Build and run the app to see the result.

Android custom dialog with round corners. (Large preview)

Android Alertdialog with animation

Let’s transform this boring Alertdialog to something more fun by adding some cool animation to it.

24- Open styles.xml file and add the following code.

Android basically have it’s built-in animation resource files that you can directly use them.

25- Open MainActivity.java file and add the following code inside showAlertDialog function.

Android alertdialog with animation. (Large preview)

26- Here is the full code for MainActivity.java file.

27- I hope you find this tutorial helpful and if you have any question please post them in the comment below.

Источник

Оцените статью