android 底部菜单写法之FragmentTabHost

android底部菜单写法很多种类,今天用的是FragmentTabHost:代码很简单:

Mainacitivity中代码:BaseActivity继承的FragmentActivity

@ContentView(R.layout.activity_main)
public class MainActivity extends BaseActivity {
    private String[] names = {"书架", "书城", "我的"};
    private String[] tags = {"bookshelf", "bookshop", "aboutme"};
    private Class[] fragmentClass = {BookshelfFragment.class, BookshopFragment.class, AboutmeFragment.class};
    private int[] images = {R.drawable.tab_bookshelf_selector, R.drawable.tab_bookshop_selector, R.drawable.tab_aboutme_selector,};
    @ViewInject(android.R.id.tabhost)
    private FragmentTabHost tabHost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        tabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
        tabHost.getTabWidget().setDividerDrawable(null);
        for (int i = 0; i < images.length; i++) {
            TabHost.TabSpec tabSpec = tabHost.newTabSpec(tags[i]).setIndicator(getImageView(i));
            tabHost.addTab(tabSpec, fragmentClass[i], null);
            tabHost.getTabWidget().getChildAt(i).setBackgroundResource(R.color.material_grey_100);
        }
    }
    private View getImageView(int index) {
        View view = View.inflate(this, R.layout.item_tab, null);
        ImageView iv = (ImageView) view.findViewById(R.id.iv_icon);
        TextView tv = (TextView) view.findViewById(R.id.tv_name);
        iv.setImageResource(images[index]);
        tv.setText(names[index]);
        return view;
    }
}


布局文件activity_main代码,注意其中的几个id



    
        
        
    

布局文件item_tab代码:



    
    

选择器tab_textcolor_selector代码:



    
    

最终效果:

android 底部菜单写法之FragmentTabHost_第1张图片





你可能感兴趣的:(android,FragmentTabHost)