- Android-er
- Monday, May 20, 2013
- Add and Remove view dynamically
- 23 comments:
- Android-er
- Friday, November 27, 2015
- Add and Remove view dynamically, keep track of child views
- 6 comments:
- Программное добавление и удаление виджета
- Добавляем виджет
- Удаляем виджет
- activity_main.xml
- layer1.xml
- layer2.xml
- Dynamic ViewPager in android
- ViewPager
Android-er
For Android development, from beginner to beginner.
Monday, May 20, 2013
Add and Remove view dynamically
This exercise demonstrate how to add and remove view dynamically at run-time. When user click on the Add button, new view will be added. When user click on Remove button, the corresponding view will be removed.
MainActivity.java
23 comments:
why to take so much efforts?
when you can manage it by visibility VISIBLE and GONE.
in there any particular reason to use this approach?
— It’s asked from another one.
— I think set it VISIBLE/GONE, and dynamic add/remove is differency. At least I can insert un-limited view at run-time according user action. If use VISIBLE/GONE, I have to know number of view while coding.
— Actually, when I see the «another one» question, I also think about use VISIBLE/GONE in first instance:)
how to toast the edittext values of inflated layout on clicking a submit button?
I modified some lines of code. I have one extra Submit button. On clicking Submit it has to Toast all EditText values of Inflated layout. But its toasting only the last item.
public class MainActivity extends Activity <
EditText textIn,textOut;
Button buttonAdd, submit;
LinearLayout container;
@Override
protected void onCreate(Bundle savedInstanceState) <
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textIn = (EditText) findViewById(R.id.textin);
buttonAdd = (Button) findViewById(R.id.add);
container = (LinearLayout) findViewById(R.id.container);
submit = (Button) findViewById(R.id.Submit);
@Override
public void onClick(View arg0) <
LayoutInflater layoutInflater = (LayoutInflater) getBaseContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addView = layoutInflater.inflate(R.layout.row, null);
textOut = (EditText) addView
.findViewById(R.id.editText);
Button buttonRemove = (Button) addView
.findViewById(R.id.remove);
buttonRemove.setOnClickListener(new OnClickListener() <
@Override
public void onClick(View v) <
((LinearLayout) addView.getParent())
.removeView(addView);
>
>);
@Override
public void onClick(View v) <
String s1 = textOut.getText().toString();
Toast.makeText(getBaseContext(), «»+s1, Toast.LENGTH_SHORT).show();
>
>);
hello DroidLearner said,
You have many textOut, but with one submit button only. How can you select which textOut to submit?
You define EditText textOut as a global variable, for sure it keep the last value.
How to get the all textout value??Please Help ASAP..
Thank you very much, this is exactly what I was searching for! 🙂
But how do I get the values out of all the TextViews the user adds?
hey can v reload the whole dynamic view on some condition .. i tried but it threw up some error
When portrait to Landscape or Landscape to portrait, the added views are gone. how can we prevent it?
Thanks buddy, can resolve my problem, I share my code to create a dynamic form based on your method
private static void createFormularioTipo1(String Nombre, final String ParametroRespuesta,ScrollView scv_container) <
LayoutInflater layoutInflater =
(LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addView = layoutInflater.inflate(R.layout.layout_tipo_1, null);
TextView etiqueta = (TextView)addView.findViewById(R.id.tv_layout_tipo_1_etiqueta);
final EditText texto =(EditText)addView.findViewById(R.id.et_layout_tipo_1_texto);
etiqueta.setText(Nombre);
Button buscar = (Button)addView.findViewById(R.id.btn_layout_tipo_1_consultar_buscar);
buscar.setText(act.getResources().getString(R.string.cabecera_2_consultar));
buscar.setCompoundDrawables(act.getResources().getDrawable(R.drawable.ic_action_search),null,null,null);
buscar.setOnClickListener(new View.OnClickListener() <
@Override
public void onClick(View v) <
Functions.AlertDialogShow(act,ctx,ParametroRespuesta);
>
>);
Thanks dude.. Helped me alot 🙂
How does this line work:
If I add more than one view, how is it determined which exact view is to be removed?
Sorry for my english is too bad to explain, so I post in another example: Add and Remove view dynamically, keep track of child views.
Hello and sorry for my bad english. I’m try to put a AutocompleteTextView, an EditText and a button Add starting from your example in this and last post.
Without fortune. How can i achieve that, and retrieve or cancel data too? a link to a tutorial or where i can find more about it is ok.
thanks in advance
How to added spinner dynamically. with different data in each spinner. when load it from Json data. each spinner should load with different data. how to achieve it.
how to grand total for all total??
Hi, This is most helpful article, I have spend tow days for dynamic creation. Finally I found this article, Thanks author .
Many of asking, how to get all textOut value for the layout ?
LinearLayout ll = …
final int childcount = ll.getChildCount();
for (int i = 0; i February 15, 2017 at 11:09 AM
I am using arraylist to store all values. How can I remove particular value for particular view to be removed?
sir how to save the data in ,sir help me plezzz
Nice work, I was looking for something exactly like this. 🙂
Thanks a lot!!
Источник
Android-er
For Android development, from beginner to beginner.
Friday, November 27, 2015
Add and Remove view dynamically, keep track of child views
I have a old example of «Add and Remove view dynamically». Somebody ask how the Remove button keep track of the views. So I modify the example to explain in more details.
In this example, when user click on the Add button, it will create a child View, addView. The addView have a Button, buttonRemove. The buttonRemove have its own OnClickListener object. The OnClickListener object refer to the specified addView when it is created.
That means the OnClickListener object of the buttonRemove in the first child view(«abc») not the same object in the second child view(«abcdef»), not the same object in the third child view(«abcdefghi»). All have its own individual OnClickListener object. And each OnClickListener object refer to a specified addView object. Such that it can keep track of the child Views, addView.
MainActivity.java
layout/row.xml, the layout of the child views.
6 comments:
Hey i am just taking reference your code but how i will compare the text of your child view because if its will be same no problem but if its different then i need to replace the text with top parent to nearest child. Is it possible i am using AutocompleteTextview and Assign the same Text to the new View ??
How you compare strings?
In Java, to compare strings, using StringA.equal(StringB), NOT (StringA==StringB).
Yes exactly i am doing same but like in your row.xml i have taken a Autocompletetextview which is inflating There is no issue regarding the add view but when i remove and specific view from Number 1 to 10 suppose i remove view number 5 so the text in 4 and 6 should be same so i need to save the selected content to some list but in view how can i do that ?? i stuck only when i remove a particular specially not from bottom ??
Sorry, I don’t understand your problem.
I tried to change the TextView to AutoCompleteTextView, and found no any problem. Please read Add and Remove view dynamically, with EditText/AutoCompleteTextView inside.
how to get each edit text value which will we add can you put code with example like one more button is submit then when click on it i get all text from all edittext and set in one textview.
i am doing a task in which i will show spinner dynamically with add button event. now on each click event of spinner of dynamic spinner i have some value related to selected item of spinners. but the issue is when i have multiple spinners and selects item from lets say 2nd spinner item the related value of 2nd spinner should be changed but it is changing the last displayed textview value which is related to last spinner.
like i have
1) spinner with textview(dynamic)
2)on each event of add button spinner and textview will displays
3)now lets say i will click button for 4 times which displays(4 spinners and textviews)
4)the process should be select an item of 1st spinner the related data should be display on its textview(related data on textview will come from db)
5)the process should continue many times
6)Now the issue is when i select 2nd spinner item or 3rd spinner item its related data must display on textview 2nd and textview 3rd. but when i selected 2nd or 3rd spinner item the related data is displaying on 4th spinners texview
Источник
Программное добавление и удаление виджета
Обычно мы размещаем виджеты через XML. Но можно это делать и программно. Такой подход используется при динамическом размещении, когда неизвестно, сколько элементов должно быть на экране.
Добавляем виджет
Допустим у нас есть простейшая разметка.
Пустая компоновка LinearLayout с идентификатором mainlayout не содержит вложенных виджетов. Через метод addView(view) класса LinearLayout мы можем добавить нужный нам элемент.
Удаляем виджет
Существует и обратный метод для удаления вида — removeView(), а также метод removeAllViews(), удаляющий все дочерние элементы родителя. Рассмотрим следующий пример. Создадим разметку, где компонент LinearLayout с идентификатором master будет родителем для будущих элементов, которые мы будем добавлять или удалять:
activity_main.xml
Создадим пару дополнительных макетов, которые будет дочерними элементами для FrameLayout. Мы будем управлять ими программно.
layer1.xml
layer2.xml
Напишем код, который будет добавлять или удалять компоновки через флажки.
Обратите внимание, что добавление идёт в том порядке, как мы отмечаем флажки. Если мы отметим флажком второй CheckBox, то сначала на экране появится блок с компоновкой layer2.xml, а уже ниже компоновка layer1.xml. На скриншоте представлен этот вариант.
Получить доступ к дочерним элементам можно через методы getChildCount() и getChildAt().
Источник
Dynamic ViewPager in android
ViewPager
ViewPager is one of the most commonly used component in android. It has its unique functionality of swiping between pages. It is used with Fragment as it manages lifecycle of each page by its own.
But it increases complexity when it is implemented with fragment. Sometimes with less care in fragments leads to memory leaks. It also has a role to play in implementing the adapter. When we have multiple View pagers in our app, we can avoid FragmentPager Adapter and FragmentStatePager.
Usually , FragmentPager is used when there is a fixed number of pages . The fragments visited is kept in the memory until it is destroyed which leads to a significant amount of memory.
In case of FragmentStatePager , it can work with large number of pages with memory saving. It only stores the data or saved instance of visited page and destroys the fragments when it is not visible.
It is a good way to create our view pager by extending PagerAdapter . Instead of creating fragments , create custom views and pass it to Pager class. Here our views are independent of lifecycle callbacks.
Now set this pager adapter to ViewPager ,
In this way , the view pager is implemented with the static list of views. We can dynamically add or delete a view from view pager.
Here notifyDataSetChanged() is useful only when there is change in view pager data (either items in view pager is added or removed) , not to refresh contents of fragment.
To add view Dynamically:
To delete any page dynamically:
View pager Layout:
It is as simple as adding or removing an item from List View . It is fine to use views instead of fragment in view pager to reduce complexity.
Источник