Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically set a TextView width and height to Wrap Content

I am writing a table programmatically from an SQLite database.

In a loop I am generating needed TextViews and am attempting to wrap the data in a TextView called descCol when the data is longer than the existing screen allows.

Suggestions to do this were offered in the following link: Setting width to wrap_content for TextView through code

However when using either of the suggested methods I'm getting a java.lang.NullPointerException.

Here's my code example:

TextView descCol = new TextView(this);
descCol.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;

In this case debug shows it throws a java.lang.NullPointerException on the getLayoutParams() line.

Also I've tried:

TextView descCol = new TextView(this);
ViewGroup.LayoutParams params = descCol.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
params.width = ViewGroup.LayoutParams.WRAP_CONTENT;
descCol.setLayoutParams(params);

In this case debug shows it throws a java.lang.NullPointerException on the params.height line.

Debug shows that in either case after performing the getLayoutParams() method, params is equal to null, apparently throwing the exception.

I've tried to assign other parameters first to descCol (textcolor, text, gravity etc.) prior to the getLayoutParams() but get the same result.

Suggestions as to how to avoid the java.lang.NullPointerException would be appreciated.

like image 827
Bill Avatar asked Nov 18 '17 23:11

Bill


2 Answers

Also I was able to accomplish my task programmatically by simply using the setWidth and setHeight methods.

textview.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
textview.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
like image 122
Bill Avatar answered Sep 23 '22 00:09

Bill


Try this way:

  LinearLayout.LayoutParams textParam = new LinearLayout.LayoutParams
                        (LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f);

    textView.setLayoutParams(textParam);
like image 41
Yunus Kulyyev Avatar answered Sep 21 '22 00:09

Yunus Kulyyev