【发布时间】: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