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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With