Android项目底部Tab实现

底部菜单实现:
FragmentTabHost用法:
1.Activity要继承FragmentActivity
2.调用setup()方法
3.添加TabSpec

主页面:

public class MainActivity extends AppCompatActivity {
    private FragmentTabHost mTabhost;
    private LayoutInflater mInflater;
    private List mTab = new ArrayList<>(5);


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initTab();

    }

    private void initTab() {
        Tab tab_home = new Tab(R.string.home, R.mipmap.icon_home, HomeFragment.class);
        Tab tab_hot = new Tab(R.string.hot, R.mipmap.icon_hot, HotFragment.class);
        Tab tab_catagoryme = new Tab(R.string.catagory, R.mipmap.icon_discover, CategotyFragment
                .class);
        Tab tab_cart = new Tab(R.string.cart, R.mipmap.icon_cart, CartFragment.class);
        Tab tab_mine = new Tab(R.string.mine, R.mipmap.icon_user, MineFragment.class);

        mTab.add(tab_home);
        mTab.add(tab_hot);
        mTab.add(tab_catagoryme);
        mTab.add(tab_cart);
        mTab.add(tab_mine);

        mInflater = LayoutInflater.from(this);
        mTabhost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabhost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);


        for (Tab tab : mTab) {
            TabHost.TabSpec tabSpec = mTabhost.newTabSpec(getString(tab.getTitle()));
            tabSpec.setIndicator(buildIndicator(tab));
            mTabhost.addTab(tabSpec, tab.getFragment(), null);
        }
    }

    private View buildIndicator(Tab tab) {
        View view = mInflater.inflate(R.layout.tab_indicator, null);
        ImageView img = (ImageView) view.findViewById(R.id.icon_tab);
        TextView text = (TextView) view.findViewById(R.id.txt_indicator);

        img.setBackgroundResource(tab.getIcon());
        text.setText(tab.getTitle());
        return view;
    }
}

xml文件:




    


    

        
    




Tab的bean文件

public class Tab {
    private int title;
    private int icon;
    private Class fragment;



    public Tab(int title, int icon, Class fragment) {
        this.title = title;
        this.icon = icon;
        this.fragment = fragment;
    }

    public int getIcon() {
        return icon;
    }

    public void setIcon(int icon) {
        this.icon = icon;
    }

    public Class getFragment() {
        return fragment;
    }

    public void setFragment(Class fragment) {
        this.fragment = fragment;
    }

    public int getTitle() {

        return title;
    }

    public void setTitle(int title) {
        this.title = title;
    }
}

你可能感兴趣的:(Android项目底部Tab实现)