FragmentTabHost

在activity_main_layout里添加FragmentTabHost

android.support.v4.app.FragmentTabHost的id必须是:@android:id/tabhost




    
        
        
        
        
        
    

MainActivity.java

public class MainActivity extends AppCompatActivity implements TabHost.OnTabChangeListener {
    private FragmentTabHost mTabHost;

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

        mTabHost = (FragmentTabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup(this, getSupportFragmentManager(), R.id.activity_main_real_tab_content);
        mTabHost.getTabWidget().setDividerDrawable(null);
        mTabHost.setOnTabChangedListener(this);
        initTab();
    }

    private void initTab() {
        String[] tabs = TabDb.getTabsTxt();
        Class[] clz = TabDb.getFragment();
        for (int i = 0; i < tabs.length; i++) {
            TabHost.TabSpec spec = mTabHost.newTabSpec(tabs[i]).setIndicator(getView(i));
            mTabHost.addTab(spec, clz[i], null);
            mTabHost.setTag(i);
        }
    }

    private View getView(int i) {
        View view = LayoutInflater.from(this).inflate(R.layout.footer_tabs, null);
        TextView textView = (TextView) view.findViewById(R.id.footer_tabs_text_view);
        textView.setText(TabDb.getTabsTxt()[i]);
        if (i == 0) {
            textView.setTextColor(getResources().getColor(R.color.main_green));
            ((ImageView) view.findViewById(R.id.footer_tabs_image_view)).setImageResource(
                    TabDb.getTabImgLight()[i]
            );
        } else {
            ((ImageView) view.findViewById(R.id.footer_tabs_image_view)).setImageResource(
                    TabDb.getTabImg()[i]
            );
        }
        return view;
    }

    @Override
    public void onTabChanged(String s) {
        updateTab();
    }

    private void updateTab() {
        TabWidget tabw = mTabHost.getTabWidget();
        for (int i = 0; i < tabw.getChildCount(); i++) {
            View view = tabw.getChildAt(i);
            ImageView iconIv = (ImageView) view.findViewById(R.id.footer_tabs_image_view);
            TextView tipTv = (TextView) view.findViewById(R.id.footer_tabs_text_view);
            if (i == mTabHost.getCurrentTab()) {
                iconIv.setImageResource(TabDb.getTabImgLight()[i]);
                tipTv.setTextColor(getResources().getColor(R.color.main_green));
            } else {
                iconIv.setImageResource(TabDb.getTabImg()[i]);
                tipTv.setTextColor(getResources().getColor(R.color.foot_text_gray));
            }
        }
    }
}

你可能感兴趣的:(FragmentTabHost)