在片段中以编程方式将布局包含在视图中

4
好的,我有一个片段,我想在它的xml文件中包含另一个通过编程膨胀的布局。
片段:
public class zGoal_Fragment extends Fragment{

    private LinearLayout todayView;
    private View view;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.main_goal_view, container, false);
        todayView = (LinearLayout)view.findViewById(R.id.todayView);

        return view;
    }
}

XML文件片段的翻译:

xml文件片段:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="fill_parent"
          android:id="@+id/todayView"
>
</LinearLayout>

我想在上面的XML中以编程方式包含一个XML布局:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/goalEditLayout"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="100dp"
          android:background="@color/test_color_two"
>
</LinearLayout>

我尝试了几种不同的方法,但都导致了“在空对象引用上”的错误...请帮忙:)

我已经为您的查询添加了一个答案。您可以使用ViewStubs,或者更好的方法是使用include标签,并将另一个文件的布局添加到目标xml文件中... - Adithya Upadhya
2个回答

2
我想你正在寻找的解决方案是Android ViewStubs。这些是动态填充的布局。
更多信息,您可以参考以下内容: 如何在Android中使用View Stub

https://developer.android.com/reference/android/view/ViewStub.html

然而,如果您不希望在运行时将一个布局膨胀到另一个布局中,则可以尝试使用标签:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="fill_parent"
          android:id="@+id/todayView">

         <include layout="@layout/your_layout_file_name"/>
</LinearLayout>

如果我们的回答帮助了您,请别忘了给它点赞并标记为正确答案(在答案旁边有箭头和勾号)。 :) - Adithya Upadhya

0
你尝试过这样的方法吗:
LinearLayout child = getLayoutInflater().inflate(R.layout.goalEditLayout, null);
todayView.addView(child);

编辑: 在onCreateView内部:

LinearLayout inflatedLayout = (LinearLayout) inflater.inflate(R.layout.goalEditLayout, todayView, true);

我可能错了,但在片段中调用getLayoutInflater()时不能没有bundle参数。 :/ - Zeta

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接