使用FragmentTabHost切换碎片(这是一个仿购物车的主界面)

来吧,皮卡丘们,先看效果:这个效果其实挺简单的,以前没有用过这个走了很多弯路,用了他之后才知道有多方便,以后再写这种效果就可以直接CV了,来,上代码:

使用FragmentTabHost切换碎片(这是一个仿购物车的主界面)_第1张图片


其中有两个主要点:android:id/tabhost 和 @+id/realtabcontent,前者为系统定义的 TabHost 导航条,后者为主体内容(即 Tab 点击时,加载 Fragment 区域)



    

        

            

            
            
            

            
            

        
    


然后在整一个加载文字的布局




    



为了实现当点击哪个按钮的时候可以改变相应的图片和文字的颜色,所以我们弄一个自定义一个选择器:

改变图片的:因为我是把图片放在mipmap里的,所以是mipmap/shouye2x

首页的:



    
    
附近的:



    
    
购物车的:



    
    
个人中心的



    
    

改变字体颜色的:text_change




    
准备工作做好之后那我们就上代码吧

public class MainActivity extends FragmentActivity {
    private FragmentTabHost mTabhost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 实例化tabhost对象,得到tabhost
        mTabhost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        //通过使用 mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent)将两者结合起来
        mTabhost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
        //文字
        String[] titles = new String[]{"首页", "附近", "购物车", "个人中心"};
        //图片
        int[] selectors = new int[]{R.drawable.homepage, R.drawable.fujin,
                R.drawable.cart, R.drawable.center};
        //类
        Class[] fragmentName = new Class[]{
                HomePageFragment.class,
                NearbyFragment.class,
                ShoppingCartFragment.class,
                PeopleCenterFragment.class,};
        //得到一个布局管理器是为了加载我们文字的布局
        LayoutInflater inflater = getLayoutInflater();
        for (int i = 0; i < titles.length; i++) {
            View inflate = inflater.inflate(R.layout.tab_item, null);

            TextView tv_title = (TextView) inflate.findViewById(R.id.tv_title);
            tv_title.setText(titles[i]);
            Drawable top = getResources().getDrawable(selectors[i]);
            tv_title.setCompoundDrawablesWithIntrinsicBounds(null, top, null, null);
            // 为每一个tab设置图标和选项卡, 将spec和Fragment添加到每个选项卡中
            mTabhost.addTab(mTabhost.newTabSpec(titles[i]).setIndicator(inflate), fragmentName[i], null);
        }

    }
}

这样就OK了,很方便的




你可能感兴趣的:(Android)