【问题标题】:Include layout in view programmatically within a fragment在片段中以编程方式在视图中包含布局
【发布时间】:2017-03-13 00:09:08
【问题描述】:

好的,所以我有一个片段,我想在它的 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文件:

<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 甚至更好,使用包含标签并在目标 xml 文件中添加另一个文件的布局...

标签: java android xml android-layout android-fragments


【解决方案1】:

你有没有尝试过这样的事情:

LinearLayout child = getLayoutInflater().inflate(R.layout.goalEditLayout, null);
todayView.addView(child);

编辑: onCreateView 内部:

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

【讨论】:

  • 我可能错了,但是如果没有 bundle 参数,片段中的 getLayoutInflater() 就无法调用。 ://
【解决方案2】:

我想您正在寻找的解决方案是 Android ViewStubs。这些是动态膨胀的布局。

有关更多信息,您可以参考以下内容:

How to use View Stub in android

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

但是,如果您希望在运行时期间在另一个布局中膨胀一个布局,您可以尝试使用 include 标签:

<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>

【讨论】:

  • 如果我们的答案对您有所帮助,请不要忘记投票并将其标记为正确(答案旁边的箭头和勾号)。 :)
猜你喜欢
  • 1970-01-01
  • 2019-04-25
  • 2013-09-30
  • 2019-12-18
  • 1970-01-01
  • 2021-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多