Android - How to change fragments in the Navigation Drawer

前端 未结 4 1582
甜味超标
甜味超标 2020-11-30 05:22

I\'m fairly new to Android programming, but have been doing pretty well until now. I\'ve read a lot of answers to this question but can\'t seem to make mine work. Basically

4条回答
  •  执念已碎
    2020-11-30 05:44

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments
    
        FragmentManager fragmentManager = getSupportFragmentManager();
    
        if (position == 0) {  
            fragmentManager.beginTransaction() 
                 .replace(R.id.container, FirstFragment.newInstance())  
                 .commit();  
        } else if (position == 1) {  
           fragmentManager.beginTransaction()  
             .replace(R.id.container, SecondFragment.newInstance())  
             .commit();  
        } else if (position == 2) {  
           fragmentManager.beginTransaction()  
             .replace(R.id.container, ThridFragment.newInstance())  
             .commit();  
        }  
    
    }
    

    and create fragment

    public class FirstFragment extends Fragment {  
    
       public static FirstFragment newInstance() {
         FirstFragment fragment = new FirstFragment();  
         return fragment;  
       }  
    
       public FirstFragment() {  
       }  
    
       @Override  
       public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
           View rootView = inflater.inflate(R.layout.fragment_first, container, false);  
           return rootView;  
       }  
    
       @Override  
       public void onAttach(Activity activity) {  
           super.onAttach(activity);  
           ((MainActivity) activity).onSectionAttached(1);  
       }  
    }  
    

提交回复
热议问题