Android笔记——自定义TabLayout之title与icon

自定义TabLayout

自定义底端TabLayout

总布局

实现的是底端TabLayout



    

    


TabLayout自定义布局



    

    


Selector

color



    
    
    
    


icon

因为三个图标的selector是一样的,所以就取了一个



    
    
    


代码

主要分以下两步实现,若想看怎么自定义,请直接跳到最后的getTabView

initContent();
initTab();
String[] title = {"个人","推荐","动态"};

ContentPagerAdapter

class ContentPagerAdapter extends FragmentPagerAdapter {

        public ContentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return tabFragments.get(position);
        }

        @Override
        public int getCount() {
            return tabIndicators.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return tabIndicators.get(position);
        }
}

initContent

private void initContent(){
        tabIndicators = new ArrayList<>();
        for(int i = 0; i < title.length; i++){
            tabIndicators.add(title[i]);
        }
        tabFragments = new ArrayList<>();
        tabFragments.add(new UserFragment());
        tabFragments.add(new RecommendFragment());
        tabFragments.add(new DynamicsFragment());

        contentAdapter = new ContentPagerAdapter(getSupportFragmentManager());
        vp_home.setAdapter(contentAdapter);
}

initTab

private void initTab(){
        tab_home.setTabMode(TabLayout.MODE_FIXED);
        tab_home.setSelectedTabIndicatorHeight(0);
        ViewCompat.setElevation(tab_home,getResources().getDimension(R.dimen.elevation_5));
        tab_home.setupWithViewPager(vp_home);
        for(int i = 0; i < title.length;i++){
            TabLayout.Tab tab = tab_home.getTabAt(i);
            if(tab != null){
                tab.setCustomView(getTabView(i));
            }
        }
        tab_home.getTabAt(1).select();
}

getTabView

private View getTabView(int position){
        TypedArray prodIcon_tab = getResources().obtainTypedArray
                (R.array.prodIcon_tab);//图片资源ID数组
        View view = LayoutInflater.from(this).inflate(R.layout.tab_item,null);
        TextView tab_text = (TextView)view.findViewById(R.id.tab_text);
        tab_text.setText(title[position]);
        ImageView tab_icon = (ImageView)view.findViewById(R.id.tab_icon);
        tab_icon.setImageResource(prodIcon_tab.getResourceId(position,0));
        return view;
}

你可能感兴趣的:(Android笔记——自定义TabLayout之title与icon)