How to switch between fragments during onclick?

前端 未结 2 1808
[愿得一人]
[愿得一人] 2020-12-01 17:08

I have a project I\'m trying to do. I ran into a little issue and I\'m not sure how to get around it. Below is an image of the application so far.

What I would like

相关标签:
2条回答
  • 2020-12-01 17:20
    private void openFragment (int number) {
    
            Fragment fragment = new Fragment();
    
            switch (number) {
                case FRAGMENT_1:
                    fragment = new *Fragment1*();
                    break;
    
                case FRAGMENT_2:
                    fragment = new *Fragment2*();
                    break;
            }
    
            getSupportFragmentManager().beginTransaction()
                    .replace(R.id.fragment_frame, fragment)
                    .commit();
        }
    
    0 讨论(0)
  • 2020-12-01 17:28

    Not sure what's the minimal fix to get your code working, but have you looked at using a Navigation Drawer to switch between the fragments? It looks to me like the example in the official docs matches pretty much exactly what you want to achieve.

    A key is to have some kind of container for the currently displayed fragment (instead of using <fragment> like in your XML). For example:

     <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    

    Then, switching fragments goes something like this:

    Fragment fragment = new Fragment2();
    // Insert the fragment by replacing any existing fragment
    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction()
                   .replace(R.id.content_frame, fragment)
                   .commit();
    

    Further reading: Add a Fragment to an Activity at Runtime in Android developer docs.

    0 讨论(0)
提交回复
热议问题