【问题标题】:Null Pointer Exception when setting LayoutParams设置 LayoutParams 时出现空指针异常
【发布时间】:2013-09-02 12:14:38
【问题描述】:

我以编程方式在活动中创建了按钮,而不是在 xml 文件中。然后我想在这个链接中设置它 LayoutParams:How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?

但是当我尝试启动时,我遇到了异常。

这是我的代码:

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

为什么我的应用会引发异常?谢谢。

【问题讨论】:

  • 可能 LogCat 指向空指针的行上方的行将变为空,但为了帮助您,最好更新您发布错误的问题。

标签: android nullpointerexception imagebutton layoutparams


【解决方案1】:

改变这个:

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 一起出现。

【讨论】:

  • LayoutParams.MATCH_PARENT需要设置为RelativeLayoutParams.MATCH_PARENT,因为LayoutParams有多种类型
【解决方案2】:

在我看来,它看起来像

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

getLayoutParams() 用于已设置 paramsView。因此,您需要先将它们设置为 go,然后再尝试将它们设置为 get 以用于另一个 View

【讨论】:

    【解决方案3】:

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

    根据View.java中getLayoutParams()的注解,你的ImageButton是程序创建的,调用方法时没有附加到父ViewGroup,所以返回null。

    【讨论】:

      猜你喜欢
      • 2021-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多