Search code examples
javaandroidlistandroid-fragmentsandroid-listfragment

Should a fragment have a different class to the activity it is used in?


I intend to build a simple activity, with a list and a more detailed viewing panel. The list is populated with data from reading from a file. My question is whether the code for the two fragments should be in one activity, or in two separate activities and then called by another activity?? Thanks for the help!!!


Solution

  • You should use one activity. To place both frags in screen use smth like this

    <LinearLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    
        <fragment
            android:id="@+id/frag1"
            android:name="your.pckg.frag1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"/>        
        <fragment
            android:id="@+id/frag2"
            android:name="your.pckg.frag2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="2"/>
    </LinearLayout>
    

    Both frags are separated classes (in example case it is your.pckg.frag1 class and your.pckg.frag2 class)