Android以编程方式将布局视图添加到另一个布局

时间:2014-09-08 19:39:01

标签: android android-layout

我有一个垂直方向的LinearLayout,我想添加另一个带有两个子元素的水平LinearLayout。

这是我的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>

以下是应该完成工作的代码:

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;

我在contacts_tab_menulist.addView(listItem)上得到一个nullPointerException。我做错了什么?

2 个答案:

答案 0 :(得分:2)

尝试替换

contacts_tab_menulist = (LinearLayout) getActivity().findViewById(R.id.contacts_tab_menulist);

contacts_tab_menulist = (LinearLayout) rootView.findViewById(R.id.contacts_tab_menulist);

答案 1 :(得分:1)

从膨胀的视图中获取视图,因为View的膨胀并不意味着它是当前的活动视图:

    contacts_tab_menulist = (LinearLayout) rootView.findViewById(R.id.contacts_tab_menulist);