HXSP1947
HXSP1947

Reputation: 1351

TextView not appearing, Android

Thank in advance for the help.

I am trying to add a vertically weighted TextView object to a LinearLayout.

//root container
LinearLayout rootContainer = new LinearLayout(activity);
rootContainer.setOrientation(LinearLayout.HORIZONTAL);
rootContainer.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.MATCH_PARENT,1f));
rootContainer.setBackgroundColor(Color.parseColor("#000000"));

//Text View
TextView instructions = new TextView(activity);
instructions.setLayoutParams(new LinearLayout.LayoutParams(0,
            LayoutParams.MATCH_PARENT,.7f));
instructions.setText(survey.instructions);
instructions.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
instructions.setBackgroundColor(Color.RED);
rootContainer.addView(instructions);

When I use the above code I get a blank screen. However, if I comment out

instructions.setLayoutParams(new LinearLayout.LayoutParams(0,
            LayoutParams.MATCH_PARENT,.7f));

The TextView appears (albeit not the size that I want it).

From everything I've seen this this is the way to produce a weighted TextView (weighted vertically by the size of the screen). What am I doing wrong?

Upvotes: 0

Views: 67

Answers (3)

N.T.
N.T.

Reputation: 2611

I think the accepted answer on this question is wrong. The reason why this is not working is because the LinearLayout was set with a vertical orientation, while the the TextView was constructed with a width weight:

instructions.setLayoutParams(new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT,.7f));

It should have been:

instructions.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0, .7f));

Moreover, since the TextView was the only child of the LinearLayout, the weightSum attribute should have been set to 1 in order to achieve the 70% ratio:

rootContainer.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,             ViewGroup.LayoutParams.MATCH_PARENT));
rootContainer.setWeightSum(1);

Upvotes: 0

Hussein El Feky
Hussein El Feky

Reputation: 6707

You can just replace what you have with this:

instructions.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT, 0.7f));

The reason why it was not shown on app startup was because when defining a view in java code, it defines it with pixels, so when you set the width to 0, it will certainly be invisible. It is unlike defining it in a xml layout file.

Hope that helps.

Upvotes: 1

Melvin Mauricio
Melvin Mauricio

Reputation: 387

The code

instructions.setLayoutParams(new LinearLayout.LayoutParams(0,
        LayoutParams.MATCH_PARENT,.7f));

sets your width of text view to 0 means that it will not be viewed try replacing 0 with some values or LayoutParams.WRAP_CONTENT

Upvotes: 0

Related Questions