Pregunta

I has a Sliding ViewPager with about 5 pages. Each layout is inflated like this:

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

Now I want to check if a condition is true and if Yes, I want to inflate the gridpage1 layout first, then another layout on top of it.

How can i do this? All I need is the help on inflating two views one on top of the other.

¿Fue útil?

Solución

Inflating a view basically just means creating it from an XML file and returning it.

In your specific case, you just need to return your fragment content view from the onCreateView function. This must be a single view, so if your condition is true and you want 2 views do the following:

  1. Create a FrameLayout view yourself programmatically

    Something like: FrameLayout frameLayout = new FrameLayout(context);

  2. Add the 1st view to your FrameLayout after inflating it

    Either do frameLayout.addView(inflater.inflate(R.layout.gridpage1,frameLayout,false)); or even inflater.inflate(R.layout.gridpage1,frameLayout,true); is enough because true tells it to add the view to the container.

  3. Add the 2nd view to your FrameLayout after inflating it

  4. Return the FrameLayout from your onCreateView

Addition:

How to save the reference to each view:

Option 1:

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

Option 2:

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

Otros consejos

You can use the <include /> tag in your main layout and then hide/show the views you want with setVisibility(View.GONE/VISIBLE). For example:

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

And in your Fragment, you can inflate only the root layout and find the other views by ID.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top