setLayoutParams()返回null ptr

时间:2015-02-25 09:25:08

标签: android android-linearlayout

我有一个像这样的xml布局结构:

<?xml version="1.0" encoding="utf-8">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:id="@+id/ll"
    android:layout_marginRight="54dp">

    <TextView
       android:id="+@id/tv"
       ....
    />
</LinearLayout

我正在尝试以编程方式增加线性布局的marginRight。在我的Java代码中,我有这样的东西:

LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(0,0,100,0);

if(something is true){
  ll.setLayoutParams(lp);
}
else {
   //do nothing
}

我在行ll.setLayoutParams(lp);

上得到一个null ptr异常

1 个答案:

答案 0 :(得分:1)

“ll”没有父级,因此您无法为其设置边距,设置填充,或将边距设置为“tv”