【问题标题】:Android overlapping layoutsAndroid 重叠布局
【发布时间】:2013-07-21 08:16:01
【问题描述】:

我有一个大约 5 页的滑动 ViewPager。每个布局都是这样膨胀的:

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

现在我想检查一个条件是否为真,如果是,我想先填充 gridpage1 布局,然后在其上添加另一个布局。

我该怎么做?我所需要的只是帮助将两个视图叠加在一起。

【问题讨论】:

    标签: android layout inflate


    【解决方案1】:

    膨胀视图基本上只是意味着从 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. 从您的onCreateView 返回FrameLayout

    加法:

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

    选项 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(...);
    

    【讨论】:

    • 使用这个选项,我可以隐藏视图吗?我只希望在任何给定时间显示 1 个。喜欢切换开关...
    • 当然,您可以保留对每一个的引用或使用其 id 找到它,然后调用 view.setVisibility(..)
    • 好的,我会先给它,如果我需要帮助会发布。谢谢
    • 另一个选项不是隐藏和显示 frameLayout 中的每个视图,而是相应地调用 removeView(v1) 和 addView(v2) .. 只要您保留对 v1 和 v2 的引用,它们就不会被释放
    • 好的,一个问题,当我添加到 frameLayout 时,我如何获得对 Views 的引用
    【解决方案2】:

    您可以在主布局中使用<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>
    

    并且在您的 Fragment 中,您可以仅扩展根布局并通过 ID 查找其他视图。

    【讨论】:

    • ViewStub 可能更适合这种情况。
    猜你喜欢
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多