[英]Android Add Layout View to another Layout programatically
I have a LinearLayout with Vertical orientation and I would like to add another horizontal LinearLayout with two childs. 我有一个垂直方向的LinearLayout,我想添加另一个水平的LinearLayout和两个孩子。
Here is my xml layout: 这是我的xml布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/Gray_background"
android:orientation="vertical" >
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginTop="10dp"
android:background="@color/GrayStroke" />
<LinearLayout
android:id="@+id/contacts_tab_menulist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/White"
android:orientation="vertical" >
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="@color/GrayStroke" /> </LinearLayout>
Here is the code which should do the job: 这是应该完成工作的代码:
View rootView = inflater.inflate(R.layout.contacts_tab,
container, false);
contacts_tab_menulist = (LinearLayout) getActivity().findViewById(R.id.contacts_tab_menulist);
// add LayoutParams
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 35);
LinearLayout listItem = new LinearLayout(getActivity());
listItem.setLayoutParams(lparams);
listItem.setOrientation(LinearLayout.HORIZONTAL);
AspectRatioImageView icon = new AspectRatioImageView(getActivity());
LinearLayout.LayoutParams ic_params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 25);
icon.setImageResource(R.drawable.contacts_add_contact);
icon.setLayoutParams(ic_params);
listItem.addView(icon);
TextView title = new TextView(getActivity());
LinearLayout.LayoutParams t_params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
title.setText("Add Contact");
title.setId(0);
title.setLayoutParams(t_params);
listItem.addView(title);
contacts_tab_menulist.addView(listItem);
return rootView;
I get a nullPointerException on contacts_tab_menulist.addView(listItem)
. 我在
contacts_tab_menulist.addView(listItem)
上遇到nullPointerException。 What am I doing wrong? 我究竟做错了什么?
Try replacing 尝试更换
contacts_tab_menulist = (LinearLayout) getActivity().findViewById(R.id.contacts_tab_menulist);
with 同
contacts_tab_menulist = (LinearLayout) rootView.findViewById(R.id.contacts_tab_menulist);
从膨胀的视图中获取视图,因为膨胀View
并不意味着它是当前的活动视图:
contacts_tab_menulist = (LinearLayout) rootView.findViewById(R.id.contacts_tab_menulist);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.