I need to assign a unique tab id to my tabs created using viewpager and tablayout?

后端 未结 3 1574
清酒与你
清酒与你 2021-01-11 23:59

I created an Tab based application using viewpager and Tablayout. When i click a button new tabs are created with a child fragment.

What I need is to assign differe

3条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-12 00:17

    Here is my solution for the question:

    First, create an id file under res/values named ids.xml:

    
    
        
        
    
    

    Then, within the code where tabs are created, do the following:

    for (int i = 0; i< tabLayout.getTabCount(); i++) {
            TabLayout.Tab mTab = tabLayout.getTabAt(i);
            if (mTab != null) {
                switch (i){
                    case 0:
                        View tabViewOne = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(i);
                        tabViewOne.setId(R.id.tab_id_one);
                        //ect..
                        break;
                    case 1:
                        View tabViewTwo = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(i);
                        tabViewTwo.setId(R.id.tab_id_two);
                        //ect..
                        break;
                    case 2:
                        //etc..
                }
            }
        }
    

    Note: Views tabViewOne and tabViewTwo can be made global variables where it will give access to their ids anywhere within the class/activity/fragment.

提交回复
热议问题