Android TabHost Center active Tab

2020-07-24 05:19发布

问题:

Is it possible to change Android Tabs that if you press one, it comes to the center of the TabHost. Only 3 Tabs are visible, doesn't matter how many there are. Like in the Android 4.0 Google Music App! If it is, how would you do that?

Thank you!

回答1:

I did find the answer myself.
If somebody else needs it, this should do it:

    final HorizontalScrollView mHorizontalScrollView;
    float scale = getResources().getDisplayMetrics().density;
    final double tabWidth = (int) (150 * scale + 0.5f);

    for (int i = 0; i < tabHost.getTabWidget().getTabCount(); i++) {
        tabHost.getTabWidget().getChildTabViewAt(i).getLayoutParams().width = (int) tabWidth;
    }

    final double screenWidth = getWindowManager().getDefaultDisplay()
            .getWidth();
    mHorizontalScrollView = (HorizontalScrollView) findViewById(R.id.hscrollview);

    tabHost.setOnTabChangedListener(new OnTabChangeListener() {

        @Override
        public void onTabChanged(String tabId) {
            int nrOfShownCompleteTabs = ((int) (Math.floor(screenWidth
                    / tabWidth) - 1) / 2) * 2;
            int remainingSpace = (int) ((screenWidth - tabWidth - (tabWidth * nrOfShownCompleteTabs)) / 2);

            int a = (int) (tabHost.getCurrentTab() * tabWidth);
            int b = (int) ((int) (nrOfShownCompleteTabs / 2) * tabWidth);
            int offset = (a - b) - remainingSpace;

            mHorizontalScrollView.scrollTo(offset, 0);
        }
    });