Switch to Android FragmentActivity

Asked 1 years ago, Updated 1 years ago, 60 views

I'm making an Android app.

As I progressed a little bit, even if screen A is shown at first, screen B is already onCreate.

Because B will float Google Maps and draw a picture.

I got a lot of advice and when I used FragmentActivity, I put two fragments on one FragmentActivity from the beginning, and I saw both of them become onCraate.

(However, even if AB made two fragments, AB Fragment occupies all of the Fragment Activity.)

 <fragment
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        class="com.example.googlemap_test.leftFragment"
        android:id="@+id/leftView"/>
    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.example.googlemap_test.rightFragment"
        android:id="@+id/rightView"/>

Two fragments were attached with these xml codes.

But if you do it this way, when you want to change the screen from left fragment to right fragment, It is difficult to use replace because it was not created as an object in Main.

Seeing this situation, I think I made the wrong choice from the beginning.

I wonder if there is a way to solve it or another way. Please give me some advice.

잘Please let me know if you know anything wrong!

android actvitiy

2022-09-21 22:03

1 Answers

The replace() function of the FragmentTransaction class is essentially equivalent to removing an existing fragment and then adding (int, fragment, string) a new fragment. The intention of the code you wrote is to preload the left, right fragment, and if you use replace() to move between fragments, as described, the right fragment will ride the end routine when going to right -> left. This means that when you move back to right, you will create a new fragment and add it to the activity, which is likely to be inconsistent with the intention (=preload).

And (as you will know if you have tested it) add() and replace() using instances of fragments already added to the activity via XML do not work. (Because the fragments of the instance have already been added to the activity, the screen change will not occur as intended)

I think show(Fragment)/hide(Fragmet) is the way to work without any major changes in the current code. Refer to the code below to control the exposure of fragments when changing status.

supportFragmentManager.beginTransaction()
    .setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
    .show(rightFragmeht)
    .commit()

supportFragmentManager.beginTransaction()
    .setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
    .hide(leftFragment)
    .commit()


2022-09-21 22:03

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.