我正在尝试从活动中创建一个新的LinearLayout,以将其插入到另一个视图中,这就是我的方法
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setBackgroundResource(R.color.customBlue);
linearLayout.getLayoutParams().height= ViewGroup.LayoutParams.WRAP_CONTENT;
linearLayout.getLayoutParams().width= ViewGroup.LayoutParams.MATCH_PARENT;
但是我得到这个错误
java.lang.NullPointerException: Attempt to write to field 'int
android.view.ViewGroup$LayoutParams.height' on a null object reference
那么如何通过编程将LinearLayout的宽度和高度设置为match_parent或wrap_content?这是怎么了?
答案 0 :(得分:0)
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
linearLayout.setLayoutParams(params);
答案 1 :(得分:0)
您做错了,您试图设置一个空的布局参数高度,因为在创建布局对象之后,您还没有将布局参数设置为LinearLayout。
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
ll.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT));
`