Align Icons in Tab Layout To The Left

后端 未结 6 1472
被撕碎了的回忆
被撕碎了的回忆 2020-12-18 00:44

Hello I have created a tab layout in my activity. This is the main .xml file:




        
6条回答
  •  自闭症患者
    2020-12-18 01:24

    TabLayout also support custom views instead of TabView.

    1.Create your tab item layout.The main idea is we should use specify id for ImageView @android:id/icon and for TextView @android:id/text1

    R.layout.custom_tab_item

    
    
        
    
        
    
    

    2. And TabLayout xml file

     
    

    3. Create tabLayout using custom views, and remove bottom margin, which was set up by default 8dp

    mTabLayout = (TabLayout) findViewById(R.id.tab_layout);     
    mTabLayout.addTab(createTab(text1,icon1));
    mTabLayout.addTab(createTab(text2,icon2));
    
    private TabLayout.Tab createTab(String text, Drawable icon){
        TabLayout.Tab tab = mTabLayout.newTab().setText(text).setIcon(icon).setCustomView(R.layout.custom_tab_item);
    
        // remove imageView bottom margin
        if (tab.getCustomView() != null){
            ImageView imageView = (ImageView) tab.getCustomView().findViewById(android.R.id.icon);
            ViewGroup.MarginLayoutParams lp = ((ViewGroup.MarginLayoutParams) imageView.getLayoutParams());
            lp.bottomMargin = 0;
            imageView.requestLayout();
        }
    
        return tab;
    }
    

    Expected result.

提交回复
热议问题