BoyUnderTheMoon
BoyUnderTheMoon

Reputation: 771

Android programatically add layout resource to view

I have a scrollview in an activity that I want to populate. Each item I want to add to the list is made up of several views (text view, image view, etc). Instead of programmatically creating each view, and adding it to a linear layout, and then adding that to the containing layout, is it possible to instead create a predefined layout resource with these items and instead add it to the view and programmatically change the item contents?

Essentially, is it possible to do something like:

container.addView(R.layout.listItem);

And if so, how could I access views within the list item to change them?

Upvotes: 1

Views: 169

Answers (2)

tynn
tynn

Reputation: 39853

It's just what inflate(int, ViewGroup, boolean) does with the third parameter attachToRoot set to true

getLayoutInflater().inflate(R.layout.listItem, container, true);

After that everything is straightforward

container.findViewById(R.id.text_view)

Upvotes: 3

convexHull
convexHull

Reputation: 1881

You have to "inflate" your view by LayoutInflater. For example like this:

View view = LayoutInflater.from(context).inflate(R.layout.listItem, container, true);

or View view = LayoutInflater.from(context).inflate(R.layout.listItem, container, false); container.addView(view);

Upvotes: 1

Related Questions