Android Studio——TabWiget组件实现(带图标签)

最终效果图如下:(选图有点丑emmm)

本次实验主要涉及了:
1.标签设置时文字和图片不能同时显示问题
解决方法:修改AndroidManifest.xml里的 android:theme变成android:theme="@android:style/Theme.Black"
另外,网上也有说可以自定义View,暂时没试
2.由于白色的标签文字看不清楚,于是想到改变字的颜色,参考https://www.cnblogs.com/yuxuan007/p/7238980.html
最终MainActivity.java代码如下:

private TabHost tabhost;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tabhost = getTabHost();
    tv=(TextView)findViewById(R.id.sj);
    //View tabIndicator = LayoutInflater.from(this).inflate(R.layout.activity_receive_top, getTabWidget(), false);
    //增加选项卡名
    Intent ReceiveIntent = new Intent(MainActivity.this,ReceiveActivity.class);
    tabhost.addTab(tabhost.newTabSpec("tag1").setIndicator("收件箱",getResources().getDrawable(R.drawable.ic_tab_receive)).setContent(ReceiveIntent));
    Intent SendIntent = new Intent(MainActivity.this,SendActivity.class);
    tabhost.addTab(tabhost.newTabSpec("tag2").setIndicator("发件箱",getResources().getDrawable(R.drawable.ic_tab_send)).setContent(SendIntent));
    Intent DeletedIntent = new Intent(MainActivity.this,DeletedActivity.class);
    tabhost.addTab(tabhost.newTabSpec("tag3").setIndicator("已删除",getResources().getDrawable(R.drawable.ic_tab_deleted)).setContent(DeletedIntent));
    tabhost.setCurrentTabByTag("tag1");
    //选项卡切换事件处理
    tabhost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
        @Override
        public void onTabChanged(String tabId) {
            upDateTab(tabhost);
            Toast.makeText(MainActivity.this,"当前选中:"+tabId+"标签",Toast.LENGTH_SHORT).show();
        }
    });
}
/**
 * 更新文字颜色。
 *
 * @param mTabHost
 */
private void upDateTab(TabHost mTabHost) {
    for (int i = 0; i < mTabHost.getTabWidget().getChildCount(); i++) {
        TextView tv = (TextView) mTabHost.getTabWidget().getChildAt(i).findViewById(android.R.id.title);
        if (mTabHost.getCurrentTab() == i) {//选中
            tv.setTextColor(this.getResources().getColor(R.color.colorAccent));
        } else {//不选中
            tv.setTextColor(this.getResources().getColor(R.color.colorPrimary));
        }
    }
}

好啦,结束了!

猜你喜欢

转载自www.cnblogs.com/pjshhh/p/12578938.html