简体   繁体   中英

Can I start two fragments in one NavHostFragment?

I have a fragment screen with with two sections 1) image card and 2) tablayout with view pager which they are split into two XML files and two Fragment lifecycle java file. Also, I have one NAV host fragment in my activity and one NAV graph. Can I start the two XMLs at once in the NAV host fragment such that I can display the two XMLs, section 1) and 2), vertically.

Remark: I DON'T have room to add/create XML/NAVHostFragment to include the two XMLs. Anything in Java will work for me.

Anyone has any insight on how to do that under such situation?

Here is what I started:

activity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_scrollFlags="scroll">

    <fragment
        android:id="@+id/navhostfragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/navgraph" />
</LinearLayout>

imagecard.xml

<androidx.cardview.widget.CardView
     android:id="@+id/cardview"
     android:layout_width="match_parent"
     android:layout_height="match_parent">
    
         <ImageView
            android:id="@+id/imageview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    
</androidx.cardview.widget.CardView>

viewpager.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tab"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">


    </com.google.android.material.tabs.TabLayout>


    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewpager2"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

A Possible Solution is:

  1. Create a Fragment MainFragment with a viewpager.
  2. Set that fragment as Start destination in Navgraph.
  3. Load cardimage and tabLayout in the MainFragment s viewpager
  4. Set the Orientation of the Main Viewpager to vertical by calling setOrientation()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM