Android重叠布局

时间:2013-07-21 08:16:02

标签: android layout inflate

我有一个大约5页的Sliding ViewPager。每个布局都膨胀如下:

  public static class SectionFragment extends Fragment {
  ...
  @Override
  public View onCreateView(LayoutInflater inflater, ...) {
      ...
      rootView = inflater.inflate(R.layout.gridpage1,container,false);
      ...
  }

现在我想检查一个条件是否为真,如果是,我想首先膨胀gridpage1布局,然后是另一个布局。

我该怎么做?我所需要的只是帮助将两个视图一个接一个地膨胀。

2 个答案:

答案 0 :(得分:0)

您可以在主布局中使用<include />标记,然后使用setVisibility(View.GONE/VISIBLE)隐藏/显示所需的视图。 例如:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <include android:id="@+id/gridpage1_layout" layout="@layout/gridpage1"/>
    <include android:id="@+id/gridpage2_layout" layout="@layout/gridpage2"/>
...

</RelativeLayout>

在您的片段中,您只能对根布局进行充气,并按ID查找其他视图。

答案 1 :(得分:0)

扩展视图基本上只是意味着从XML文件创建并返回它。

在您的特定情况下,您只需要从onCreateView函数返回片段内容视图。这必须是单个视图,因此如果您的条件为真且您想要2个视图,请执行以下操作:

  1. 以编程方式自行创建FrameLayout视图

    类似于:FrameLayout frameLayout = new FrameLayout(context);

  2. 在第一个视图充气后将其添加到FrameLayout

    frameLayout.addView(inflater.inflate(R.layout.gridpage1,frameLayout,false));  甚至inflater.inflate(R.layout.gridpage1,frameLayout,true);就足够了,因为true告诉它将视图添加到容器中。

  3. 第二个视图在充气后添加到FrameLayout

  4. FrameLayout
  5. 返回onCreateView

    <强>增加:

    如何保存对每个视图的引用:

    选项1:

    View v1 = inflater.inflate(R.layout.gridpage1,frameLayout,false);
    this.v1Reference = v1;
    frameLayout.addView(v1);
    

    选项2:

    inflater.inflate(R.layout.gridpage1,frameLayout,true);
    this.v1Reference = frameLayout.findViewById(...);
    
相关问题