- Как установить ширину и высоту DialogFragment?
- Gotcha # 13: Макеты DialogFragment
- onCreateDialog Insanity
- Но подождите, есть еще!
- В итоге
- Implementing DialogFragment in Android
- What is DialogFragment?
- Three steps of creating custom Dialog
- Methods of DialogFragment
- Project Setup
- Creating Simple Dialog — Example
- Creating an Alert Dialog — Example
- Creating Dialog containing data(shared with Activity/Fragment)
- Conclusion
Как установить ширину и высоту DialogFragment?
Я указываю макет моего DialogFragment в файле макета xml (назовем его layout_mydialogfragment.xml ) и его layout_width и layout_height частности (каждый будет 100dp , скажем так). Затем я раздуваю этот макет в моем методе onCreateView(. ) следующим образом:
К сожалению, я обнаружил, что, когда появляется мой диалог (DialogFragment), он не layout_width и layout_height указанные в его файле макета xml (и мой диалог сжимается или расширяется в зависимости от содержимого). Кто-нибудь знает, может ли или как я могу получить мой диалог, чтобы уважать layout_width и layout_height указанные в его файле макета xml? В настоящий момент мне нужно снова указать ширину и высоту моего диалога в моем методе onResume() в onResume() следующим образом …
… И, следовательно, нежелательно, помните, чтобы вносить любые изменения в ширину и высоту диалога в двух местах.
Если вы конвертируете непосредственно из значений ресурсов:
Затем укажите match_parent в вашем макете для диалога:
Вам нужно только беспокоиться о одном месте (поместите его в свой DialogFragment#onResume ). Это не идеально, но, по крайней мере, он работает для того, чтобы RelativeLayout был корневым файлом макета вашего диалогового окна.
Я получил фиксированный размер DialogFragment, определяющий следующее в главном макете XML (LinearLayout в моем случае):
Я закончил переопределять Fragment.onResume() и захватил атрибуты из базового диалога, а затем задал параметры width / height. Я установил match_parent высоту / ширину match_parent в match_parent . Обратите внимание, что этот код, похоже, уважает поля, определенные мной в макете xml.
Фрагмент из блога Adil:
Я пытался сделать диалог уважением к ширине и высоте моего макета, не указав фиксированный размер программно.
Я понял, что android:windowMinWidthMinor и android:windowMinWidthMajor вызывают проблему. Несмотря на то, что они не были включены в тему моей Activity или Dialog , они все равно применялись к теме « Activity .
Я придумал три возможных решения.
Решение 1. Создайте настраиваемую тему диалога и используйте ее при создании диалога в диалоговом окне « DialogFragment .
Решение 2. Создайте настраиваемую тему, которая будет использоваться в ContextThemeWrapper который будет служить Context для диалога. Используйте это, если вы не хотите создавать настраиваемую тему диалога (например, если вы хотите использовать тему, заданную android:dialogTheme ).
Решение 3 (с помощью AlertDialog ): выполните android:windowMinWidthMinor и android:windowMinWidthMajor в ContextThemeWrapper созданный AlertDialog$Builder .
Когда мне нужно сделать DialogFragment немного шире, я устанавливаю minWidth:
Gotcha # 13: Макеты DialogFragment
На самом деле это отвращение.
При создании DialogFragment вы можете переопределить onCreateView (который передает ViewGroup для прикрепления вашего макета .xml) или onCreateDialog , а это не так.
Вы не должны переопределять оба метода tho, потому что вы, скорее всего, будете путать Android с тем, когда или когда макет вашего диалога был завышен! WTF?
Выбор того, следует ли переопределять OnCreateDialog или OnCreateView зависит от того, как вы собираетесь использовать диалог.
- Если вы запустите диалог в окне (нормальное поведение), вы должны переопределить OnCreateDialog .
- Если вы намерены встраивать фрагмент диалога в существующий макет интерфейса (FAR менее распространенный), тогда вы должны переопределить OnCreateView .
Это, возможно, самое худшее в мире.
onCreateDialog Insanity
Таким образом, вы переопределяете onCreateDialog в своем DialogFragment чтобы создать индивидуальный экземпляр AlertDialog для отображения в окне. Круто. Но помните, onCreateDialog получает ViewGroup чтобы ViewGroup свой собственный .xml макет. Нет проблем, вы просто передаете значение null методу inflate .
Пусть начнется безумие.
Когда вы переопределяете onCreateDialog , Android ПОЛНОСТЬЮ ИГРАЕТ несколько атрибутов корневого узла .xml Layout, который вы раздуваете. Это включает, но, возможно, не ограничивается:
- background_color
- layout_gravity
- layout_width
- layout_height
Это почти комично, так как вам нужно установить layout_width и layout_height из КАЖДОГО .xml Layout или Android Studio, чтобы пощекотать вас красивым красным значком стыда.
Просто слово DialogFragment заставляет меня хотеть блевать. Я мог бы написать роман, наполненный Android-азартами и snafus, но этот один из самых внутренних.
Чтобы вернуться к здравомыслию, во-первых, мы объявляем стиль для восстановления JUST background_color и layout_gravity мы ожидаем:
Вышеупомянутый стиль наследуется от базовой темы для Dialogs (в примере AppCompat в этом примере).
Затем мы применяем стиль программно, чтобы вернуть значения, которые Android просто отбросил, и восстановить стандартный AlertDialog вид AlertDialog :
Приведенный выше код сделает ваш AlertDialog похожим на AlertDialog . Возможно, это достаточно хорошо.
Но подождите, есть еще!
Если вы хотите установить SPECIFIC layout_width или layout_height для своего AlertDialog когда он показан (очень вероятно), тогда угадайте, что вы еще не сделали!
Веселье продолжается, так как вы понимаете, что если вы попытаетесь установить конкретную layout_width или layout_height в своем новом стильном стиле, Android полностью игнорирует это !:
Чтобы установить ширину или высоту окна SPECIFIC, вы можете перейти к целому «nuther» и LayoutParams :
Многие люди следят за плохим примером Android, ViewGroup.LayoutParams от WindowManager.LayoutParams до более общей ViewGroup.LayoutParams , только чтобы повернуть направо и бросить ViewGroup.LayoutParams обратно в WindowManager.LayoutParams несколько строк позже. Эффективная Java будет проклята, что ненужное кастинг предлагает НИЧЕГО, кроме того, что код еще сложнее расшифровать.
Замечание: Есть несколько LayoutParams повторений LayoutParams через Android SDK – прекрасный пример радикально плохого дизайна.
В итоге
Для DialogFragment s, которые переопределяют onCreateDialog :
- Чтобы восстановить стандартный AlertDialog вид AlertDialog , создайте стиль, который устанавливает background_color = transparent и layout_gravity = center и применяет этот стиль в onCreateDialog .
- Чтобы установить конкретную layout_width и / или layout_height , сделайте это программно в onResume с LayoutParams
- Чтобы поддерживать здравомыслие, постарайтесь не думать об Android SDK.
Я установил его, установив параметры компоновки корневого элемента.
Вот способ установить ширину / высоту DialogFragment в xml. Просто заверните свою иерархию view в Framelayout (любой макет будет работать) с прозрачным фоном.
Прозрачный фон кажется особым флагом, потому что он автоматически центрирует дочерний элемент frameLayout в окне, когда вы это делаете. Вы по-прежнему получите полное затемнение позади вашего фрагмента, указывая, что ваш фрагмент является активным элементом.
Измерение в самом внешнем макете не работает в диалоговом окне. Вы можете добавить макет, где заданный размер ниже самого внешнего.
Я создаю диалог, используя AlertDialog.Builder, поэтому я использовал ответ Родриго внутри OnShowListener.
В моем случае это было вызвано align_parentBottom=»true» данный для представления внутри RelativeLayout . Удалили все alignParentBottom и изменили все макеты на вертикальные LinearLayouts и проблема исчезла.
Работа над Android 6.0 столкнулась с той же проблемой. AlertDialog будет по умолчанию предустановленной width заданной в теме, независимо от фактической width установленной в корневом Layout пользовательского вида. Я смог заставить его правильно настроить width loading_message . Не исследуя далее, кажется, что определение размеров фактических элементов и обтекание корневого Layout вокруг них заставляет его работать должным образом. Ниже представлен XML-макет диалогового окна загрузки, которое правильно устанавливает width диалогового окна. Использование этой библиотеки для анимации.
Вы можете под кодом установить ширину и высоту макета из java.
Вы можете использовать процент для ширины.
Я использовал тему Holo для этого примера.
Установите Parent Layout Layout Layout, чтобы получить общую ширину и высоту автоматически.
Одно из ранних решений почти сработало. Я попробовал что-то немного другое, и это закончилось тем, что работало на меня.
(Удостоверьтесь, что вы смотрите на его решение) Это было его решение .. Нажмите здесь Это сработало, за исключением: builder.getContext (). GetTheme (). ApplyStyle (R.style.Theme_Window_NoMinWidth, true);
Я изменил его на
Последняя строка на самом деле отличается.
Чтобы получить диалоговое окно, которое охватывает почти весь экран: Сначала определите класс ScreenParameter
Источник
Implementing DialogFragment in Android
Dialogs are one of the most common and easiest ways of interactions with users. Almost every application has some dialogs present in it. It may be an alert dialog that is shown whenever you are logging out from some application or it can be any custom dialog that is used to take input from users or display some information to the user. We use dialogs to have a quick implementation of some feature in our application without creating an Activity.
For example, whenever you are connecting to a new wifi network then after selecting the wifi network, a Dialog will be opened and you can enter that password in the opened dialog and submit the details.
One of the popular implementations of Dialogs is AlertDialog. Alert Dialogs are used to alert the user before performing a particular task. For example, if you want to delete some images from the Gallery, then the Gallery app will alert you about the fact that by pressing the OK button which is the positive button, in this case, the image will be deleted permanently.
Dialogs are Awesome 🙂
So, in this blog, we will learn how to make Custom Dialogs using the DialogFragment in Android. So, let’s get started.
Here is the timeline for this blog:
- What is DialogFragment?
- Three steps of creating custom Dialog
- Methods of DialogFragment
- Project Setup
- Creating Simple Dialog — Example
- Creating an Alert Dialog — Example
- Creating Dialog containing data(shared with Activity/Fragment) — Example
- Conclusion
What is DialogFragment?
In a very simple sentence, a Dialog Fragment is a fragment that is used to make Dialogs that floats on some Activity.
DialogFragment is a utility class which extends the Fragment class. All the information regarding the Dialog or the data associated with the Dialog will be stored or managed in the Fragment only. You can use the DialogFragment in API level 11 or higher.
Since DialogFragment is associated with Fragment, so it has it’s own LifeCycle and now the Activity need not manage the lifecycle of Dialogs. Due to this reason, DialogFragments are recommended to be used while implementing Alert Dialog or any other type of Dialogs in Android and it is very easy to create a dialog fragment of our own because it requires only 3 steps. Let’s see those steps:
Three steps of creating custom Dialog
- First of all, you need to create a Kotlin/Java file for your Dialog Fragment. For example, CustomDialog.kt and this class will extend the DialogFragment() . Here in this class, all the methods related to dialogs will be there.
- After creating the class, you need to make the layout file of the dialog. According to your use-case, make the layout of your Dialog Fragment.
- And finally, you need to call your custom dialog from your Activity.
Methods of DialogFragment
There are certain methods that are associated with DialogFragment and we can use then in our Dialog Fragment class. Some of the most commonly used methods are:
- onAttach(): This is called when a fragment is first attached with its context.
- onCreate(): The initial creation of a fragment is done in onCreate and it is called after the onAttach.
- onCreateDialog(): This is used to build your custom dialog. It is mostly used for showing some AlertDialog(provided by Android).
- onCreateView(): This is used to supply the contents of the Dialog and this is entirely responsible for drawing the Dialog. It is generally used for creating custom dialogs. If you are creating an AlertDialog, then this method is not needed, only onCreateDialog is sufficient in that case.
- onViewCreated(): This is called when the Dialog is created. This is used to ensure that the view is created.
- onDestroy(): Thisis used to destroy the DialogFragement.
The order of execution of the above methods will be: onAttach -> onCreate -> onCreateDialog -> onCreateView -> onViewCreated -> onDestroy.
Project Setup
- Project Name: DialogFrament-Example
- Language Used: Kotlin
We will be sharing the data between the DialogFragment and the Activity and for this, we will be using Shared ViewModel. So, add the dependency of LiveData and ViewModel in you app level build.gradle file
Creating Simple Dialog — Example
In this example, we will be having a Dialog Fragment that will contain 2 text views(one for the title and other for subtitle) and 2 buttons (one for positive button and other for negative button). So, it is going to be a mock of AlertDialog.
Here, we will pass the title and subtitle text from the Activity. If you want to hardcode the title and subtitle then it is totally upon you.
So, First of all, add one button on the MainActivty so that whenever we click on that button the dialog will be opened.
Here is the code for activity_main.xml :
Now create a SimpleDialog class (under the root directory, right-click > New > Kotlin File/Class) and also, create a layout file named fragment_simple_dialog.xml .
The following is the code for fragment_simple_dialog.xml :
Here, we are having a title, a subtitle, and two buttons(for positive and negative response).
Add the below code in you SimpleDialog.kt file:
Here is the description of the above code:
- The newInstance() method is used to take the title and subtitle form the Activity.
- The onCreateView() method is responsible for creating the Dialog Fragment.
- In the onViewCreated() we are performing the tasks that need to be done after the creation of Dialog. For example, taking out the title and subtitle and setting it in the text view of the SimpleDialog.
- The setupView() is a user-defined function that is helping in setting the text in SimpleDialog.
- The setupClickListener() is an another user-defined function that is helping in setting all the click listeners of the SimpleDialog.
On clicking the positive/negative button, the dialog will be closed with the help of dismiss() method. You can change it according to your use-case.
Now, from the MainActivtiy, you need to open the Dialog on button click. So, following is the code for the same:
Here, I am passing the title and subtitle from the Activity.
Now, run your app and click on the button to see the dialog.
Creating an Alert Dialog — Example
If you want to use the AlertDialog provided by Android instead of your own custom dialog, then all you need to do is override the onCreateDialog method and create your AlertDialog there. In this case, you need not override the onCreateView method.
So, in the SimpleDialog.kt file, the following code will be there:
Creating Dialog containing data(shared with Activity/Fragment)
In this example, we will be having one EditText in the DialogFragment and a button. On clicking the button, the text in the EditText will be displayed on the MainActivtiy .
For this, we will use the concept of SharedViewModel. If you are not familiar with SharedViewModel, then you can read our blog on that topic from here.
NOTE: Don’t forget to add the dependency of LiveData and ViewModel.
Let’s first start with the MainActivity. In the activity_main.xml file, we need to add one button and one text view for displaying the name. So, the final code of the activity_main.xml will be:
Now, create a class named DialogWithData and SharedViewModel .
The following is the code for SharedViewModel.kt :
On the button click of the Dialog, the sendName() method will be called with the text in EditText and the name will be observed in the MainActivity.
The following is the code of DialogWithData.kt file:
On the click of the submit button, the sendName() method of the SharedViewModel is called.
Now, the name need to be observed in the MainActivity and also we need to implement the click listener of the button to open the DialogWithData fragment. So, the final code of MainActivtiy will be:
Now, you can run the application and enter some data in the EditText and see the text in MainActivity.
This is how you can share the data of the DialogFragment with the Activity. For further improvements, you can check if the values in the EditText is null or not. If it is null then you can show some error Toast and if it is not null then you can simply update the TextView.
This is all about DialogFragments.
Conclusion
In this blog, we learned how to implement DialogFragment in our Android Application. We saw that the traditional Alert Dialogs are no longer recommended. So, we need to use the DialogFragment to implement Dialogs. We did one example on DialogFragment to have a clear understanding of the same.
Источник