在this示例之后,我仅能创建带有图标的SlidingTabLayout,但我想将它们居中。我需要创建自定义 View 还是有其他解决方案?
任何帮助,将不胜感激。
最佳答案
终于我明白了。这是我的代码示例...
为我创建的每个选项卡创建一个drawablestore_tab.xml
和cart_tab.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_store_white_24dp" android:state_selected="true" />
<item android:drawable="@drawable/ic_store_grey600_24dp" />
</selector>
创建自己的寻呼机适配器,该适配器从
FragmentPageAdapter
扩展public class HomePagerAdapter extends FragmentPagerAdapter {
private static int[] ICONS = new int[] {
R.drawable.store_tab,
R.drawable.cart_tab
};
// ...
@Override
public CharSequence getPageTitle(int position) {
return null;
}
@Override
public int getCount() {
return ICONS.length;
}
public int getDrawableId(int position) {
return ICONS[position];
}
}
在
SlidingTabLayout
中创建以下新方法protected ImageView createDefaultImageView(Context context) {
ImageView imageView = new ImageView(context);
int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
imageView.setPadding(padding, padding, padding, padding);
int width = (int) (getResources().getDisplayMetrics().widthPixels / mViewPager.getAdapter().getCount());
imageView.setMinimumWidth(width);
return imageView;
}
然后更改
populateTabStrip
中的SlidingTabLayout
方法private void populateTabStrip() {
final HomePagerAdapter adapter = (HomePagerAdapter) mViewPager.getAdapter();
final View.OnClickListener tabClickListener = new TabClickListener();
for (int i = 0; i < adapter.getCount(); i++) {
View tabView = null;
//TextView tabTitleView = null;
ImageView tabIconView = 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;
}*/
if (tabView == null) {
tabView = createDefaultImageView(getContext());
}
if (tabIconView == null && ImageView.class.isInstance(tabView)) {
tabIconView = (ImageView) tabView;
}
tabIconView.setImageDrawable(getResources().getDrawable(adapter.getDrawableId(i)));
if (mViewPager.getCurrentItem() == i) {
tabIconView.setSelected(true);
}
//tabTitleView.setText(adapter.getPageTitle(i));
tabView.setOnClickListener(tabClickListener);
mTabStrip.addView(tabView);
}
}
最后更改
onPageSelected
中的InternalViewPageListener
@Override
public void onPageSelected(int position) {
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
mTabStrip.getChildAt(i).setSelected(false);
}
mTabStrip.getChildAt(position).setSelected(true);
if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
mTabStrip.onViewPagerPageChanged(position, 0f);
scrollToTab(position, 0);
}
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageSelected(position);
}
}
最后结果