我在活動programmaticaly中創建按鈕,而不是在xml文件中。然後,我想在此鏈接中設置LayoutParams:How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?空指針異常設置LayoutParams
但是,當我嘗試啓動時,出現異常。
這裏是我的代碼:
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行上面的那一行指向空指針會變爲null,但是爲了幫助您更好地更新發布錯誤的問題。 – groff07