Android TabLayout setCustomView 实现带图标的tab

首先.二话不说.先看下我们实现了怎么样的效果,不符合你要求的话,就可以直接出门左转.以免耽误你的时间

Android TabLayout setCustomView 实现带图标的tab_第1张图片



,如果,你还能看到这里.说明还是比较符合你的要求的,辣么,让咱们一点一点来实现这样的效果吧

先说一下坑.在网上看到别的代码来实现这样的左边icon右边文字的tab,只需要给这个tab设置一下icon就行

tabLayout.getTabAt(0).setIcon(R.drawable.tab_home_normal);
ok,如果我们gradle的配置信息用的版本是23.0.1的话,这个的确可以实现这样的效果.但是,同样的代码.我们把该版本修改到23.2.1(我的版本信息),竟然变成了上边icon下边文字的效果了.简直了



ok,那么我们就只能用setCustomView来实现我们的效果了



首先看一下咱们的布局:

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            app:tabGravity="fill"  />
    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"/>
</android.support.design.widget.CoordinatorLayout>

基本上也就一个TabLayout和ViewPager,还是很简单的

再来看下我们的adapter是怎么写的

package com.example.imgod.testtabicontext.adapter;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import java.util.List;

/**
 * Created by imgod on 2016/3/30.
 */
public class FragmentViewPagerAdapter extends FragmentPagerAdapter {
    private List<Fragment> fragments;
    private List<String> titles;

    public FragmentViewPagerAdapter(FragmentManager manager, List<Fragment> fragments, List<String> titles) {
        super(manager);
        this.fragments = fragments;
        this.titles = titles;

    }

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

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

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

}

我们的Fragment是这么写的:

package com.example.imgod.testtabicontext.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.imgod.testtabicontext.R;


public class OneFragment extends Fragment {

    public static final String TYPE = "type";
    private View parentView;
    private TextView txt_content;

    public OneFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        parentView = inflater.inflate(R.layout.fragment_one, container, false);
        initVIew();
        return parentView;
    }

    private void initVIew() {

        txt_content = (TextView) parentView.findViewById(R.id.txt_content);
        txt_content.setText(getArguments().getString(TYPE, "Default"));
    }

    public static OneFragment newInstance(String text) {
        OneFragment fragment = new OneFragment();
        Bundle bundle = new Bundle();
        bundle.putString(TYPE, text);
        fragment.setArguments(bundle);
        return fragment;
    }


}


好了.上面都比较简单,下面就看我们的Activity的了

package com.example.imgod.testtabicontext.activitys;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.imgod.testtabicontext.R;
import com.example.imgod.testtabicontext.adapter.FragmentViewPagerAdapter;
import com.example.imgod.testtabicontext.fragments.OneFragment;

import java.util.ArrayList;
import java.util.List;


public class IconTextTabsActivityTemp1 extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private List<String> titles;
    private List<Fragment> fragments;
    private int[] tabIcons = {
            R.drawable.tab_home_normal,
            R.drawable.tab_mine_normal,
            R.drawable.tab_info_normal
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_icon_text_tabs);
        initView();
        initValue();
        initEvent();
    }

    private void initView() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        tabLayout = (TabLayout) findViewById(R.id.tabs);
    }

    private void initValue() {
        fragments = new ArrayList<>();
        fragments.add(OneFragment.newInstance("One"));
        fragments.add(OneFragment.newInstance("Two"));
        fragments.add(OneFragment.newInstance("Three"));
        titles = new ArrayList<>();
        titles.add("One");
        titles.add("Two");
        titles.add("Three");
        FragmentViewPagerAdapter adapter = new FragmentViewPagerAdapter(getSupportFragmentManager(), fragments, titles);
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
        setupTabIcons();
    }

    private void initEvent() {
    }


    private void setupTabIcons() {
        tabLayout.getTabAt(0).setCustomView(getTabView(0));
        tabLayout.getTabAt(1).setCustomView(getTabView(1));
        tabLayout.getTabAt(2).setCustomView(getTabView(2));
    }


    public View getTabView(int position) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_tab, null);
        TextView txt_title = (TextView) view.findViewById(R.id.txt_title);
        txt_title.setText(titles.get(position));
        ImageView img_title = (ImageView) view.findViewById(R.id.img_title);
        img_title.setImageResource(tabIcons[position]);
        return view;
    }

}

主要的就是getTabView方法.从布局加载一个View出来.然后设置给Tab,于是我们得到了下面的运行效果

Android TabLayout setCustomView 实现带图标的tab_第2张图片


咦,效果出来了.但是总感觉少点什么,是的,的确少点什么.我们发现Tab的文字颜色不会变了,图标一直也就一个颜色,实在是单调的很那,于是乎,我们匆匆在代码上加了这么一句话

tabLayout.setTabTextColors(Color.WHITE,Color.YELLOW);

but,然并卵.依然还是这个样子,于是乎我们只能在代码加载View和Tablayout的位置改变监听中,拿到View,然后在对他进行修改了

so,我们最后的代码是酱紫的:

package com.example.imgod.testtabicontext.activitys;

import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.imgod.testtabicontext.R;
import com.example.imgod.testtabicontext.adapter.FragmentViewPagerAdapter;
import com.example.imgod.testtabicontext.fragments.OneFragment;

import java.util.ArrayList;
import java.util.List;


public class IconTextTabsActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private List<String> titles;
    private List<Fragment> fragments;
    private int[] tabIcons = {
            R.drawable.tab_home_normal,
            R.drawable.tab_mine_normal,
            R.drawable.tab_info_normal
    };
    private int[] tabIconsPressed = {
            R.drawable.tab_home_passed,
            R.drawable.tab_mine_passed,
            R.drawable.tab_info_passed
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_icon_text_tabs);
        initView();
        initValue();
        initEvent();
    }

    private void initView() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        tabLayout = (TabLayout) findViewById(R.id.tabs);
    }

    private void initValue() {
        fragments = new ArrayList<>();
        fragments.add(OneFragment.newInstance("One"));
        fragments.add(OneFragment.newInstance("Two"));
        fragments.add(OneFragment.newInstance("Three"));
        titles = new ArrayList<>();
        titles.add("One");
        titles.add("Two");
        titles.add("Three");
        FragmentViewPagerAdapter adapter = new FragmentViewPagerAdapter(getSupportFragmentManager(), fragments, titles);
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
        setupTabIcons();
    }

    private void initEvent() {
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                changeTabSelect(tab);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                changeTabNormal(tab);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

    }

    private void changeTabSelect(TabLayout.Tab tab) {
        View view = tab.getCustomView();
        ImageView img_title = (ImageView) view.findViewById(R.id.img_title);
        TextView txt_title = (TextView) view.findViewById(R.id.txt_title);
        txt_title.setTextColor(Color.YELLOW);
        if (txt_title.getText().toString().equals("One")) {
            img_title.setImageResource(R.drawable.tab_home_passed);
            viewPager.setCurrentItem(0);
        } else if (txt_title.getText().toString().equals("Two")) {
            img_title.setImageResource(R.drawable.tab_mine_passed);
            viewPager.setCurrentItem(1);
        } else {
            img_title.setImageResource(R.drawable.tab_info_passed);
            viewPager.setCurrentItem(2);
        }
    }

    private void changeTabNormal(TabLayout.Tab tab) {
        View view = tab.getCustomView();
        ImageView img_title = (ImageView) view.findViewById(R.id.img_title);
        TextView txt_title = (TextView) view.findViewById(R.id.txt_title);
        txt_title.setTextColor(Color.WHITE);
        if (txt_title.getText().toString().equals("One")) {
            img_title.setImageResource(R.drawable.tab_home_normal);
        } else if (txt_title.getText().toString().equals("Two")) {
            img_title.setImageResource(R.drawable.tab_mine_normal);
        } else {
            img_title.setImageResource(R.drawable.tab_info_normal);
        }
    }


    private void setupTabIcons() {
        tabLayout.getTabAt(0).setCustomView(getTabView(0));
        tabLayout.getTabAt(1).setCustomView(getTabView(1));
        tabLayout.getTabAt(2).setCustomView(getTabView(2));
    }


    public View getTabView(int position) {
        View view = LayoutInflater.from(this).inflate(R.layout.item_tab, null);
        TextView txt_title = (TextView) view.findViewById(R.id.txt_title);
        txt_title.setText(titles.get(position));
        ImageView img_title = (ImageView) view.findViewById(R.id.img_title);
        img_title.setImageResource(tabIcons[position]);

        if (position == 0) {
            txt_title.setTextColor(Color.YELLOW);
            img_title.setImageResource(tabIconsPressed[position]);
        } else {
            txt_title.setTextColor(Color.WHITE);
            img_title.setImageResource(tabIcons[position]);
        }
        return view;
    }

}
最后的最后:demo的github地址: https://github.com/imgod1/TestTabIconText

你可能感兴趣的:(Android TabLayout setCustomView 实现带图标的tab)