在生成的TextView上以编程方式设置边距时出错

时间:2015-11-12 10:29:16

标签: java android android-layout textview

我生成这样的textViews:

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

当我将此代码更改为此设置边距时:

   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);

我收到此错误:

  

无法开始活动   ComponentInfo {} com.example./com.example.Activity:   java.lang.NullPointerException:尝试调用虚方法' void   android.widget.LinearLayout $ LayoutParams.setMargins(int,int,int,   INT)'在空对象引用上

如何摆脱这个错误?

感谢。

3 个答案:

答案 0 :(得分:5)

你应该创造 String type, String description, String productCode, String cutter

而不是从视图中获取它们。

答案 1 :(得分:2)

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)

答案 2 :(得分:1)

当您添加LayoutParams时,您可以开始传递TextView的实例。例如。

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