Replacing Fragments isn't working/Am I executing this the proper way?

后端 未结 5 774
滥情空心
滥情空心 2020-12-14 08:43

It\'s taken me some time to wrap my head around fragments, but this should be my last question on fragments, since I think I just about have them down. I know this is a huge

5条回答
  •  一个人的身影
    2020-12-14 09:19

    The main benefit of using fragments is to be able to make them take up portions of the screen rather than the whole screen, which is what Activities do.

    If you're just making an app for a small screen that will function like an Activity, but is coded in Fragments, just make a separate FragmentActivity for each of your Fragments.

    Make this the onCreate of your FragmentActivity:

    public void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.emptylayout);
    
        FragmentManager fragmentManager = getSupportFragmentManager(); //Or getFragmentManager() if you're not using the support library
        FragmentTransaction fragmentTransaction = fragmentManager
                .beginTransaction();
        YourFragment fragment = new YourFragment();
        fragmentTransaction.add(R.id.emptyview, fragment);
        fragmentTransaction.commit();
    }
    

    Where layout/emptylayout is an XML layout file with a FrameLayout. id/emptyview is that FrameLayout.

    If you want to use XML for your fragment's actual layout, make a separate XML layout for the actual fragment, and inflate it in the fragment's `onCreateView':

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.files, container, false);
                // Do stuff here
        return view;
    }
    

    Then just use startActivity(new Intent(getActivity(), YourFragmentActivity.class)) to launch a FragmentActivity from a Fragment.

    It seems redundant, yeah, but if you're going to be targeting larger screens later (if not, why are you bothering with fragments?), it'll make it easier in the long run.

提交回复
热议问题