jason
jason

Reputation: 7164

Error when setting margins programmatically on generated TextView

I generate textViews like this :

   TextView myView  = new TextView(this);
   myView.setText(Html.fromHtml(myString));
   linearLayout2.addView(myView);

When I change this code to this to set margins :

   TextView myView  = new TextView(this);
   myView.setText(Html.fromHtml(myString));
   LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)myView.getLayoutParams();
   params.setMargins(20, 0, 0, 0);
   myView.setLayoutParams(params);
   linearLayout2.addView(myView);

I get this error :

Unable to start activity ComponentInfo{com.example./com.example.Activity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.LinearLayout$LayoutParams.setMargins(int, int, int, int)' on a null object reference

How can I get rid of this error?

Thanks.

Upvotes: 1

Views: 583

Answers (3)

QAMAR
QAMAR

Reputation: 2694

the problem is in line

LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)myView.getLayoutParams();

myView.getLayoutParams(); will return null because it is not still added in any view. you only need first add the view in linearLayout2 after that you can get LayoutParams from view.

Alternatively you can create your own layout params and assign those to your view. like this

LinearLayout.LayoutParam params= new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)

Upvotes: 3

Farooq Arshed
Farooq Arshed

Reputation: 1963

you should create new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)

instead of getting them from the view.

Upvotes: 6

Blackbelt
Blackbelt

Reputation: 157467

you could start passing an instance of LayoutParams, when you add your TextView. E.g.

linearLayout2.addView(myView, new
       LinearLayout .LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));

Upvotes: 1

Related Questions