user1797190
user1797190

Reputation: 227

dynamic textview attributes

I want to dynamically create a textview and set attributes.

LinearLayout timeBar = (LinearLayout)findViewById(R.id.linear_layout_cells);
TextView tv = new TextView(this);
timeBar.addView(tv);

I need to be able to set the height to match parent, the width to zero, the weight will be some % of 100 and I also need to set the background colour. Is this even possible?

Any help greatly appreciated

Upvotes: 0

Views: 717

Answers (1)

wsanville
wsanville

Reputation: 37516

Yes, just make an instance of LinearLayout.LayoutParams. It has a constructor for width, height, and weight. Then, call tv.setLayoutParams().

In this case, you use LinearLayout.LayoutParams because your TextView is going inside a LinearLayout. Here's a more formal example:

LinearLayout timeBar = (LinearLayout)findViewById(R.id.linear_layout_cells);
TextView tv = new TextView(this);
float weight = 0.5f; //your value goes here.
tv.setLayoutParams(new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT, weight));
timeBar.addView(tv);

Upvotes: 2

Related Questions