How to set layout android

Creating Dynamic Layouts in Android

What are Dynamic Layouts?

Generally, we develop the layout for an Android application by creating the XML file. These are called static layouts.
Static you ask? Yes, because you can not add/delete any View Type in XML on runtime.

Dynamic layouts are developed using Java and can be used to create layouts that you would normally create using an XML file.

Why do we need them?

Let’s say we are fetching some data from our server and we want to create n number of fields/buttons/options in our layout. How do we do that using the only XML? That’s right!
But we can use Java to replicate the exact layout that we would normally create using XML.

It can be used to create LinearLayout, ScrollView, etc.which can further add TextView, EditText, RadioButtons, Checkbox inside it.

Where do Dynamic Layouts excel?

Let’s say we want to show some items in our layout that were frequently bought together(all items are of the same View Type).

There are quite a few ways to show them in our layout:
1. Adding static views in our XML(if we know the exact amount of items).
2. Using Recycler View to inflate the items in our layout.
3. Creating Dynamic Views using Java.

What if we do not know the exact number of items to be displayed and our
layout require different View Types( like 3 TextViews, 2 CheckBoxes, etc.)?

Possible solutions to tackle this problem:
1. Adding static views in our XML won’t work this time because we do not . know the exact number of views we need.
2. Using Recycler View could work but the same View Types should be grouped together in a list. There is not much flexibility in this case.
3. However, this is where Dynamic Layouts take the lead! They are flexible and can add multiple View Types to our layout in any order.

Источник

Читайте также:  Android intents что это
Оцените статью