Add and Remove Views in Android Dynamically?
How do I add and remove views such as TextView s from Android app like on the original stock Android contacts screen where you press a small icon on the right side of a field and it adds or deletes a field which consists of a TextView and an editTextView (from what I can see).
Any examples on how to achieve this?
10 Answers 10
ViewParent s in general can’t remove views, but ViewGroup s can. You need to cast your parent to a ViewGroup (if it is a ViewGroup ) to accomplish what you want.
Note that all Layout s are ViewGroup s.
I need the exact same feature described in this question. Here is my solution and source code: https://github.com/laoyang/android-dynamic-views. And you can see the video demo in action here: http://www.youtube.com/watch?v=4HeqyG6FDhQ
Layout
Basically you’ll two xml layout files:
- A horizontal LinearLayout row view with a TextEdit , a Spinner and an ImageButton for deletion.
- A vertical LinearLayout container view with just a Add new button.
Control
In the Java code, you’ll add and remove row views into the container dynamically, using inflate, addView, removeView, etc. There are some visibility control for better UX in the stock Android app. You need add a TextWatcher for the EditText view in each row: when the text is empty you need to hide the Add new button and the delete button. In my code, I wrote a void inflateEditRow(String) helper function for all the logic.
Other tricks
- Set android:animateLayoutChanges=»true» in xml to enable animation
- Use custom transparent background with pressed selector to make the buttons visually the same as the ones in the stock Android app.
Source code
The Java code of the main activity ( This explains all the logic, but quite a few properties are set in xml layout files, please refer to the Github source for complete solution):
Источник
Android — Remove views in a layout recursively
Is there a way to remove the views from a layout recursively? The function removeAllViewsInLayout() does not seem to do the task (it removes all views from a layout, but not the layout’s children views). In my program, I add some FrameLayouts dynamically over a RelativeLayout, and over these FrameLayouts I add some ImageViews and TextViews. So I want to know if I’ll have to go make my own recursive removing-view-code or if there is some available.
3 Answers 3
I think you can consider the layout as a tree. Thus, you only need a reference to the root node. If you remove it, it will be collected along with its children, since nothing else references them.
If for some reason you still see some Views after this operation, it means they belonged to a different node. You can always use the Hierarchy Viewer to «see» your UI better: http://developer.android.com/guide/developing/debugging/debugging-ui.html
It isn’t a recursive example, but I believe that it can solve your problem:
Rather than using recursion, just loop through each child and clear it if it is a FrameLayout
First, normally you should call removeAllViews() instead of removeAllViewsInLayout() read the JavaDoc for the difference.
Also neither of these functions are recursive, they only remove the views from the object it is called on. Sub-structures will not change. This might cause problems and even memory leaks, if they have references to other objects that are kept.
For example if you have the following structure:
and call removeAllViews() on top the layout sub will still refer b (and b will refer sub as parent). This means that you cannot reuse b somewhere else without first removing it parent ( sub ). If you do you will get an Exception.
Источник
Программное добавление и удаление виджета
Обычно мы размещаем виджеты через 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().
Источник