How to create an Android Tabbed Dialog containing fragments?

后端 未结 4 1735
一生所求
一生所求 2021-02-07 22:46

Can anyone point me to an example or show me how to create a simple Tabbed Dialog in Android where the contents of each tab are Fragments? All the exa

4条回答
  •  梦谈多话
    2021-02-07 23:17

    You should use a DialogFragment, TabLayout and ViewPager. For instance, your dialog fragment's view may look like this:

    
    
        
    
        
    
    

    Build your adapter and make sure you override the getPageTitleMethod, e.g:

    public class CustomAdapter extends FragmentPagerAdapter {  
       List mFragmentCollection = new ArrayList<>();  
       List mTitleCollection = new ArrayList<>();  
       public CustomAdapter(FragmentManager fm) {  
         super(fm);  
       }  
       public void addFragment(String title, Fragment fragment)  
       {  
         mTitleCollection.add(title);  
         mFragmentCollection.add(fragment);  
       }  
       //Needed for  
       @Override  
       public CharSequence getPageTitle(int position) {  
         return mTitleCollection.get(position);  
       }  
       @Override  
       public Fragment getItem(int position) {  
         return mFragmentCollection.get(position);  
       }  
       @Override  
       public int getCount() {  
         return mFragmentCollection.size();  
       }  
     }
    

    In the OnCreateView of your dialog, you should setup your viewpager with the tabLayout:

     public View onCreateView(LayoutInflater inflater,  ViewGroup container,  Bundle savedInstanceState) {  
         View rootview = inflater.inflate(R.layout.dialog_sample,container,false);  
         tabLayout = (TabLayout) rootview.findViewById(R.id.tabLayout);  
         viewPager = (ViewPager) rootview.findViewById(R.id.masterViewPager);  
         CustomAdapter adapter = new CustomAdapter(getChildFragmentManager());  
         adapter.addFragment("Boy",CustomFragment.createInstance("John"));  
         adapter.addFragment("Girl",CustomFragment.createInstance("Stacy"));  
         adapter.addFragment("Robot",CustomFragment.createInstance("Aeon"));  
         viewPager.setAdapter(adapter);  
         tabLayout.setupWithViewPager(viewPager);  
         return rootview;  
       } 
    

    I have a blog post written on it here: here.

提交回复
热议问题