简体   繁体   中英

Share a fragment with several classes?

I wonder how I can best create a progress bar fragment. It must be usable by every other class of course.

At the moment I have just a ProgressBarFragment, which has public setVisible method. Getting the Fragment through FragmentManager I can set it visible or not. But is this the right way to do these sort of actions?

public class MyActivity exetends FragmentActivity {
    void setVisibility(int visible) {
        ProgressBarFragment fragment = (ProgressBarFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_progress_bar);
        fragment.setProgressBar(visible);
    }
}

And of course I have several other Fragments which uses this code too, to trigger the progress bar.

public class ProgressBarFragment extends Fragment {
    public void setProgressBar(int visible) {
        progressBar = (ProgressBar) getActivity().findViewById(R.id.progress_bar);
        progressBar.setVisibility(visible);
    }
}

You can refactor this code into a static method of your ProgressBarFragment

class ProgressBarFragment {
    //...
    static void setVisibility(Activity parent, int visible) {
           ProgressBarFragment progressBar =
                   (ProgressBarFragment)parent.getSupportFragmentManager()
                   .findFragmentById(R.id.fragment_progress_bar);
    progressBar.setProgressBar(visible);
    //...
}

So then you will be using ProgressBarFragment.setVisibility(yourActivity, 1) everywhere.

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