Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android layout placeholder for dynamically added view

Tags:

In my Android Activity, I need to add a single View dynamically (at runtime), at a specific position in a layout. The view to be added is determined at runtime. For example, may layout may look something like this:

<LinearLayout ...>     <TextView ... />     <!-- Dynamic item to be added here -->     <TextView ... /> </LinearLayout> 

What is the best way to achieve this?

One solution is to use layout.addView(view, index), but I'd prefer not to hardcode the index.

Another solution is to use a FrameLayout as a placeholder, and place may dynamic view inside the FrameLayout, for example:

<LinearLayout ...>     <TextView ... />     <FrameLayout android:id="@+id/placeholder" />     <TextView ... /> </LinearLayout> 

Then:

findViewById(R.id.placeholder).addView(view); 

However, this adds an unnecessary view in the hierarchy.

What would be the recommended way to do this?

like image 335
Ralf Avatar asked Apr 02 '12 11:04

Ralf


1 Answers

I think that using a FrameLayout as a placeholder for your view "added at runtime" is a good solution.

I would not worry about the impact of the extra "unnecesssary" view on performance.

like image 177
Sébastien Avatar answered Sep 21 '22 19:09

Sébastien