1

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?

3
  • You can inflate the view resource and access views via the findViewById call. However I recommend using a RecyclerView. Commented Sep 16, 2016 at 13:01
  • you can inflate a layout also just like textviews in linear layout Commented Sep 16, 2016 at 13:01
  • Are you trying to create a list of views? If yes. Then you can use RecyclerView and then define your layout for a list item. Commented Sep 16, 2016 at 13:01

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

What if I'm doing this in a loop and I want to findViewById for multiple instances?
Never mind, just figured it out by doing: View view = LayoutInflater.from(getContext()).inflate(R.layout.item_exercise, null); view.findViewById ...
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.