你的位置:首页 > 操作系统

[操作系统]将Tab栏居中的方法

找到Android SlidingTabLayout源代码,在Android SlidingTabLayout源代码中有一个方法:
private void populateTabStrip();

 1 private void populateTabStrip() { 2     final PagerAdapter adapter = mViewPager.getAdapter(); 3     final View.OnClickListener tabClickListener = new TabClickListener(); 4  5     for (int i = 0; i < adapter.getCount(); i++) { 6       View tabView = null; 7       TextView tabTitleView = null; 8  9       if (mTabViewLayoutId != 0) {10         // If there is a custom tab view layout id set, try and inflate11         // it12         tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip, false);13         tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);14       }15 16       if (tabView == null) {17         tabView = createDefaultTabView(getContext());18       }19 20       if (tabTitleView == null && TextView.class.isInstance(tabView)) {21         tabTitleView = (TextView) tabView;22       }23 24       tabTitleView.setText(adapter.getPageTitle(i));25       tabView.setOnClickListener(tabClickListener);26       27       mTabStrip.addView(tabView);28     }29   }

这是谷歌官方实现的Android SlidingTabLayout添加底部选项卡Tab的代码,如果为了实现前文所述的将Tab均分水平位置空间,则需要修改此方法,在此方法中添加如下代码:

1 LinearLayout.LayoutParams layoutParams= new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1.0f);2       tabView.setLayoutParams(layoutParams);

这两段代码将tab view水平均分放置。

最终将private void populateTabStrip()改进成这样:

 1 private void populateTabStrip() { 2     final PagerAdapter adapter = mViewPager.getAdapter(); 3     final View.OnClickListener tabClickListener = new TabClickListener(); 4  5     for (int i = 0; i < adapter.getCount(); i++) { 6       View tabView = null; 7       TextView tabTitleView = null; 8  9       if (mTabViewLayoutId != 0) {10         // If there is a custom tab view layout id set, try and inflate11         // it12         tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip, false);13         tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);14       }15 16       if (tabView == null) {17         tabView = createDefaultTabView(getContext());18       }19 20       if (tabTitleView == null && TextView.class.isInstance(tabView)) {21         tabTitleView = (TextView) tabView;22       }23 24       tabTitleView.setText(adapter.getPageTitle(i));25       tabView.setOnClickListener(tabClickListener);26 27       //添加28       LinearLayout.LayoutParams layoutParams= new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1.0f);29       tabView.setLayoutParams(layoutParams);30       //添加31       32       mTabStrip.addView(tabView);33     }34   }