Stan Malcolm
Stan Malcolm

Reputation: 2790

How dynamically add/delete textViews to/from linearLayout?

I have db with name of countries(for example). My first goal is dynamically add textView for (each country) to linearLayout (android:layout_width="match_parent" android:layout_height="match_parent"). In fact adding is not a problem, but problem if the orientation of layout is horizontal and there is to much countries, but the width of layout is not enough to show all of them and they are hide!

So i need to add textViews dynamically, but if there is not enough space for new textView - add it in the next line or create new linearLayout.

I need to create new textView for each country cos than i want to make clickListener for each of them, and there is second goal...

the second goal is delete some of that textView by clicking on it, and the other textView must relocate to that empty space. Hope that my explanation is clear :) if not i will try another one.

so, i have idea how to add textView: every time when i add new textView - count the length of all previously added ones with this one and compare it with length of linearLayout, if the length of all textViews is less - add to this linLayout, else - create new lin layout and add textView there. I think this could work, it it looks ugly :) I hope there are must be more simply and pretty solution!

Talking about dynamically deleting textViews from layout - I have no idea how to do this correctly.

So I will be glad any solutions and ideas, thanks!

EDIT here is example how I want it looks like in the end:enter image description here

Upvotes: 0

Views: 871

Answers (2)

Derek Fung
Derek Fung

Reputation: 8211

LinearLayout is usually used for fixed childs.

For dynamic and large number of childs, you should use ListView or RecyclerView, which is exactly designed for what you described.

More than that, ListView and RecyclerView can reuse the child views, i.e. TextView for your case, which is needed, because view objects are heavy to create and keep in memory.

Edit:

Given your image and replies in comment. I would suggest you to use TextView with ClickableSpan, and set update the whole Text on click.

You can check ClickableSpan in the link below.

http://www.programcreek.com/java-api-examples/index.php?api=android.text.style.ClickableSpan

Upvotes: 2

Sagar Pujari
Sagar Pujari

Reputation: 343

You can use flowlayout for that. Link for flowlayout is https://github.com/ApmeM/android-flowlayout. Just inflate your views inside flowlayout. You don't have to do any calculation when inflating. If there is space available for textviews then they will be added horizontally else in the next line.

Upvotes: 0

Related Questions