Android SlidingTabLayout底部选项卡槽Tab水平居中



Android SlidingTabLayout底部选项卡槽Tab水平居中


Android SlidingTabLayout默认情况下添加的选项卡是如图1样式:

Android SlidingTabLayout底部选项卡槽Tab水平居中_第1张图片




实际的开发需求中,通常UI设计师会将这些Tab平均分配位置,以达到如图2所示效果:

Android SlidingTabLayout底部选项卡槽Tab水平居中_第2张图片



这样以实现相对较好的外观样式,但可惜的是原生的Android SlidingTabLayout代码中并不支持这样的属性设置,为实现此目标,需要自己动手修改Android SlidingTabLayout源代码以实现开发需求。
找到Android SlidingTabLayout源代码,在Android SlidingTabLayout源代码中有一个方法:
private void populateTabStrip();

private void populateTabStrip() {
		final PagerAdapter adapter = mViewPager.getAdapter();
		final View.OnClickListener tabClickListener = new TabClickListener();

		for (int i = 0; i < adapter.getCount(); i++) {
			View tabView = null;
			TextView tabTitleView = null;

			if (mTabViewLayoutId != 0) {
				// If there is a custom tab view layout id set, try and inflate
				// it
				tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip, false);
				tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
			}

			if (tabView == null) {
				tabView = createDefaultTabView(getContext());
			}

			if (tabTitleView == null && TextView.class.isInstance(tabView)) {
				tabTitleView = (TextView) tabView;
			}

			tabTitleView.setText(adapter.getPageTitle(i));
			tabView.setOnClickListener(tabClickListener);
			
			mTabStrip.addView(tabView);
		}
	}


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

LinearLayout.LayoutParams layoutParams= new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1.0f);
			tabView.setLayoutParams(layoutParams);
这两段代码将tab view水平均分放置。


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

private void populateTabStrip() {
		final PagerAdapter adapter = mViewPager.getAdapter();
		final View.OnClickListener tabClickListener = new TabClickListener();

		for (int i = 0; i < adapter.getCount(); i++) {
			View tabView = null;
			TextView tabTitleView = null;

			if (mTabViewLayoutId != 0) {
				// If there is a custom tab view layout id set, try and inflate
				// it
				tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip, false);
				tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
			}

			if (tabView == null) {
				tabView = createDefaultTabView(getContext());
			}

			if (tabTitleView == null && TextView.class.isInstance(tabView)) {
				tabTitleView = (TextView) tabView;
			}

			tabTitleView.setText(adapter.getPageTitle(i));
			tabView.setOnClickListener(tabClickListener);

			//添加by Zhang Phil
			LinearLayout.LayoutParams layoutParams= new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1.0f);
			tabView.setLayoutParams(layoutParams);
			//添加by Zhang Phil
			
			mTabStrip.addView(tabView);
		}
	}


即可实现如图2所示的底部选项卡中的子元素水平均分选项栏目的样式。

转载于:https://my.oschina.net/zhangphil/blog/1601707

你可能感兴趣的:(移动开发,ui)