I have questions about fragments in Android Tabbed Activity.

Asked 2 years ago, Updated 2 years ago, 41 views

Hello! It's nothing but Tabbed Activity has three fragments to create one activity. If the focus is matched to a specific fragment, you are going to do something by generating a thread. If you continue to run Tabbed Activity, all fragments are executed at once...

For example, if an activity has fragments A, B, and C,

When moving from A to B (when focus changes to B), I want to cause a thread only for the fragment of B. Also, when I go to A again and change to B again, I want to cause thread in B's fragment again...!

Can't a fragment be generated depending on the focus?

android

2022-09-22 21:27

1 Answers

one of the following methods to solve the problem by using a specific functions when you can.

The first way is to use TabLayout's OnTabSelectedListener. Note that callback is not invoked the first time TabLayout is inflated. Therefore, you have to consider this part and work on it.

tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
    @Override
    public void onTabSelected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }
});

The second way is to use Fragment's setUserVisibleHint(boolean) callback. When displayed on the screen, the isVisibleToUser parameter is passed to true, which can be used to perform the desired processing.

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
}


2022-09-22 21:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.