设置LayoutParams时出现Null指针异常



我在活动中以编程方式创建了按钮,而不是在xml文件中。然后我想在这个链接中设置它LayoutParams:如何在相对布局中以编程方式设置按钮的layout_align_rent_right属性?

但当我尝试启动时,我遇到了一个例外。

这是我的代码:

RelativeLayout ll2 = new RelativeLayout(this);
    //ll2.setOrientation(LinearLayout.HORIZONTAL);
    ImageButton go = new ImageButton(this);
    go.setId(cursor.getInt(cursor.getColumnIndex("_id")));
    go.setClickable(true);
    go.setBackgroundResource(R.drawable.go);
    RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams)go.getLayoutParams();
    params1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); // LogCat said I have Null Pointer Exception in this line
    go.setLayoutParams(params1);
    go.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i3 = new Intent(RecipesActivity.this, MedicineActivity.class);
            i3.putExtra(ShowRecipe, v.getId());
            i3.putExtra("Activity", "RecipesActivity");
            RecipesActivity.this.startActivity(i3);
        }
    });
    ll2.addView(go);

为什么我的应用程序抛出异常?谢谢

更改此项:

RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams)go.getLayoutParams();
params1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
go.setLayoutParams(params1);

用于:

RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
params1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
go.setLayoutParams(params1);

当你用程序创建视图时,它没有任何LayoutParams,这就是为什么你会得到NullPointerException。如果您从XML扩展视图,则视图现在带有LayoutParams。

在我看来,它看起来像

go.getLayoutParams()

返回此行中的null

 RelativeLayout.LayoutParams params1 = (RelativeLayout.LayoutParams)go.getLayoutParams();

因为你没有为它设置LayoutParams。这显然会使params1成为null,所以你在这里得到NPE

 params1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);

当您尝试在其上运行方法时(addRule(RelativeLayout.ALIGN_PARENT_RIGHT)

CCD_ 7用于已经设置了CCD_ 9的CCD_。因此,在尝试将它们get用于另一个View 之前,您需要将它们设置为go

如果此视图未附加到父ViewGroup,或者{@link#setLayoutParams(android.View.ViewGroup.LayoutParams)}未成功调用,则此方法可能返回null。当视图附加到父ViewGroup时,此方法不能返回null。

根据View.java中getLayoutParams()的注释,您的ImageButton是程序创建的,在调用该方法时没有附加到父ViewGroup,因此返回null。

最新更新