4d.coder
4d.coder

Reputation: 147

Setting the width of TextView

I am creating a TextView and setting LayoutParams for the same. But when i display the TextView the size is 0.

Below is my code:

TextView t = new TextView(getBaseContext());
t.setBackgroundResource(R.drawable.roundbox);
t.setText(new String("Hi").toCharArray(), 0, 2);

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width, height);
lp.bottomMargin = 10;
lp.gravity = Gravity.RIGHT;
t.setLayoutParams(lp);

The roundbox.xml content is:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
        <corners android:radius="8dp"/>
    <solid android:color="#FFFFFF"/>
    <stroke android:width="1dp" android:color="#4fa5d5"/>
</shape>

Can you please let me know what should i set as width and height in the LayoutParams constructor. I am setting some arbitrary value but i want the TextView size to be based on the amount of text in it.

Upvotes: 0

Views: 59

Answers (1)

KDeogharkar
KDeogharkar

Reputation: 10959

To set the width on amount of text you can set LinearLayout.LayoutParams.WRAP_CONTENT in width parameter.
It will set the height or width based on the content size.
see the documentation where you can find constant value to set the height and width as per need.

Upvotes: 1

Related Questions