简体   繁体   中英

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

Why you want fragments? You can work around activities as the problem you explained will not need fragments to work with.

In case you want to work with fragments. Create it at runtime.

Create xml layouts of each fragment separately. Create a fragment activity which will have these fragments as child The class of fragments will extend class Fragment, while the parent will be extending FragmentActivity class.

Now, for the code, each fragment will have separate code of its own, no need to drop all in a single one ie parent one. Parent will be the owner to show or hide fragments or for callbacks of views that will be in child fragment.

But I would suggest, you to go through documentation present on android developer site before implementation.

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)

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