android - 设置 LayoutParams 时出现空指针异常

标签 android nullpointerexception imagebutton layoutparams

我在 Activity 中以编程方式创建了按钮,而不是在 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);

为什么我的应用会抛出异常?谢谢。

最佳答案

改变这个:

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

当您以编程方式创建 View 时,它没有任何 LayoutParams,这就是您获得 NullPointerException 的原因。如果您从 XML 扩充 View ,则 View 现在随 LayoutParams 一起出现。

关于android - 设置 LayoutParams 时出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18521504/

相关文章:

android - NullPointerException 从文件 Android 重新缩放位图

android - 如何在 EditText 中放置按钮

android - 如何为图像按钮的图标赋予强调色?

android - Android JNI C++ 中的 "Not declared in this scope"错误

java - Android 版本从 2.2 更改为 4.2.2

android - 在 Android 中格式化 EditText 的电话号码

android - AdMob 不会在 Jelly Bean 上加载横幅,ReferenceError,AMFA_getSdkConstants 未定义

android - java.lang.NullPointerException : println needs a message

android fragment 在恢复时崩溃

c# - 在非 IE 浏览器中禁用 ASP.NET ImageButton