EGHDK
EGHDK

Reputation: 18130

Add view programatically in Android with a pre defined layout

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!

Upvotes: 0

Views: 340

Answers (1)

kabuko
kabuko

Reputation: 36312

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

TextView view = (TextView) getLayoutInflater().inflate(R.layout.sample, parentViewGroup);

Upvotes: 2

Related Questions