android 中使用TabHost控件实现微信界面的底部菜单效果_第1张图片


首先,在布局文件中的代码如下:(菜单位于底部,需要在代码中设置)


       
           
           
             
           
       
   


其次,分别作四个菜单选项的selector文件。状态为选中和默认:


    
    


注意:处于选中状态的菜单,底部还会有个发光的背景,也是将背景设置为selector,代码如下:


    




再次,在代码中得到tabhost对象,并设置对应的四个不同的tab页,代码如下:


public class MainActivity extends android.app.TabActivity
{//继承TabActivity
    String[] name = {"微信","通讯录","朋友们","设置"};
    //写好四个selector文件,内容为选中状态和默认状态时的图片
    int[] imaResid = {R.drawable.selector_tab1,R.drawable.selector_tab2,R.drawable.selector_tab3,R.drawable.selector_tab4};
    ArrayList arrayList = new ArrayList();
                                                                                                                    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tab);
        TabHost tabHost = getTabHost();
                                                                                                                         
        for (int i = 0; i < 4; i++)
        {//复用布局,创建四个View的对象,并且分别设置View对象里的控件值和图片
            View tabrl = getLayoutInflater().inflate(R.layout.tab_item, null);
            TextView tv_name = (TextView) tabrl.findViewById(R.id.tv_name);
            tv_name.setText(name[i]);
            ImageView iv_icon = (ImageView) tabrl.findViewById(R.id.iv_icon);
            iv_icon.setImageResource(imaResid[i]);
            TabSpec spec = tabHost.newTabSpec("tab" + i).setIndicator(tabrl);
            arrayList.add(spec);
        }
        tabHost.addTab(arrayList.get(0).setContent(new Intent(MainActivity.this,Tab1Activity.class)));
        tabHost.addTab(arrayList.get(1).setContent(new Intent(MainActivity.this,Tab2Activity.class)));
        tabHost.addTab(arrayList.get(2).setContent(new Intent(MainActivity.this,Tab3Activity.class)));
        tabHost.addTab(arrayList.get(3).setContent(new Intent(MainActivity.this,Tab4Activity.class)));
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.tab, menu);
        return true;
    }
}