0

I constantly find myself adding views programmatically and then one by one changing some of it's attributes. This isn't a big deal until I have to go and change something like it's height or width, because then I have to do a dpi calculation. Is there anyway to turn this:

TextView view = new TextView(activity);
view.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
view.setText(names[position]);
view.setTextColor(myColor);

To this:

TextView view = new TextView(activity);
view.setLayout(R.layout.sample);

I feel like there must be a way, but when I search online, I can't think of a word to describe what the view is doing to the layout. That's why I've chose "pre defined layout" added to a view. Is this possible? Thanks in advance!

2
  • 1
    you can always inflate a layout file and then simply add the inflated view Commented Aug 1, 2013 at 20:30
  • Inflate a layout? And I can attach it to the view?! Commented Aug 1, 2013 at 20:32

1 Answer 1

2

Not exactly, but sort of. You can programmatically inflate a view from an XML layout:

TextView view = (TextView) getLayoutInflater().inflate(R.layout.sample, parentViewGroup);
Sign up to request clarification or add additional context in comments.

8 Comments

This answer can be improved by passing parentViewGroup as the second argument to the inflate() call, instead of null. If you don't pass a view container then any layout attributes of the inflated view will be ignored!
Good point. Not sure why I didn't put it there in the first place. Edited, thanks.
I'm trying to enter parentViewGroup but I'm getting parentViewGroup cannot be resolved to a variable.
@EGHDK yeah, parentViewGroup is just a generic variable I made up to represent the parent ViewGroup. This is often the RelativeLayout or LinearLayout that you want your TextView to be in. If you want your TextView as the root view, then just substitute null for parentViewGroup.
What if I don't want to place it anywhere on that line? On my next line can I do ViewGroup.addView(view)?
|

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.