Actionbar Tabs Set Dynamic Width According To Screen Width
Solution 1:
Tab
view width is based on content/yourImage size, so to make tab view width smaller, we have to control the content/Image size. You can do this by putting ImageView
inside FrameLayout
, for example your customView
can be:
<?xml version="1.0" encoding="utf-8"?><RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/tabItemLayout"android:gravity="center"android:layout_width="wrap_content"android:layout_height="match_parent"><FrameLayoutandroid:layout_width="48dp"android:layout_height="48dp"android:layout_centerInParent="true"
><ImageViewandroid:layout_width="match_parent"android:layout_height="match_parent"android:adjustViewBounds="true"android:layout_gravity="center"android:gravity="center"android:id="@+id/imageViewTab" /></FrameLayout></RelativeLayout>
and custom style for tab:
<stylename="AppTheme"parent="@style/Theme.AppCompat.Light">
... ...
<itemname="actionBarTabStyle">@style/ActionBarTabStyle</item></style><stylename="ActionBarTabStyle"parent="@style/Widget.AppCompat.Base.ActionBar.TabView"><itemname="android:paddingLeft">0dp</item><itemname="android:paddingRight">0dp</item><itemname="android:paddingTop">0dp</item><itemname="android:paddingBottom">0dp</item></style>
[SCREENSHOT]
For FrameLayout
size with 24dp
:
For FrameLayout
size with 40dp
Solution 2:
As you're trying to achieve tabs on Actionbar which fits to width of device, one can use PagerSlidingTabStrip
or SlidingTabLayout
which gives you more flexibility in achieving tabs and its related Fragment with ViewPager
which gives your Uix more efficient and user friendly touch.
Here I'm showing how to achieve it using PagerSlidingTabStrip
PagerSlidingTabStrip.java
: Your Custom Tab View
publicclassPagerSlidingTabStripextendsHorizontalScrollView {
publicinterfaceIconTabProvider {
publicintgetPageIconResId(int position);
}
// @formatter:offprivatestaticfinalint[] ATTRS = newint[] { android.R.attr.textSize,
android.R.attr.textColor };
// @formatter:onprivate LinearLayout.LayoutParams defaultTabLayoutParams;
private LinearLayout.LayoutParams expandedTabLayoutParams;
privatefinalPageListenerpageListener=newPageListener();
public OnPageChangeListener delegatePageListener;
private LinearLayout tabsContainer;
private ViewPager pager;
privateint tabCount;
privateintcurrentPosition=0;
privatefloatcurrentPositionOffset=0f;
private Paint rectPaint;
private Paint dividerPaint;
privateintcurrentPageSelected=0; // Fix : ICON SELECTORprivateintindicatorColor=0xFF666666;
privateintunderlineColor=0x1A000000;
privateintdividerColor=0x1A000000;
privatebooleanshouldExpand=false;
privatebooleantextAllCaps=true;
privateintscrollOffset=52;
privateintindicatorHeight=8;
privateintunderlineHeight=2;
privateintdividerPadding=12;
privateinttabPadding=24;
privateintdividerWidth=1;
privateinttabTextSize=12;
privateinttabTextColor=0xFF666666;
privateTypefacetabTypeface=null;
privateinttabTypefaceStyle= Typeface.BOLD;
privateintlastScrollX=0;
privateinttabBackgroundResId= R.drawable.background_tab;
private Locale locale;
publicPagerSlidingTabStrip(Context context) {
this(context, null);
}
publicPagerSlidingTabStrip(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
publicPagerSlidingTabStrip(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
setFillViewport(true);
setWillNotDraw(false);
tabsContainer = newLinearLayout(context);
tabsContainer.setOrientation(LinearLayout.HORIZONTAL);
tabsContainer.setLayoutParams(newLayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
addView(tabsContainer);
DisplayMetricsdm= getResources().getDisplayMetrics();
scrollOffset = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, scrollOffset, dm);
indicatorHeight = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, indicatorHeight, dm);
underlineHeight = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, underlineHeight, dm);
dividerPadding = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, dividerPadding, dm);
tabPadding = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, tabPadding, dm);
dividerWidth = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP, dividerWidth, dm);
tabTextSize = (int) TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_SP, tabTextSize, dm);
// get system attrs (android:textSize and android:textColor)TypedArraya= context.obtainStyledAttributes(attrs, ATTRS);
tabTextSize = a.getDimensionPixelSize(0, tabTextSize);
tabTextColor = a.getColor(1, tabTextColor);
a.recycle();
// get custom attrs
a = context.obtainStyledAttributes(attrs,
R.styleable.PagerSlidingTabStrip);
indicatorColor = a.getColor(
R.styleable.PagerSlidingTabStrip_pstsIndicatorColor,
indicatorColor);
underlineColor = a.getColor(
R.styleable.PagerSlidingTabStrip_pstsUnderlineColor,
underlineColor);
dividerColor = a
.getColor(R.styleable.PagerSlidingTabStrip_pstsDividerColor,
dividerColor);
indicatorHeight = a.getDimensionPixelSize(
R.styleable.PagerSlidingTabStrip_pstsIndicatorHeight,
indicatorHeight);
underlineHeight = a.getDimensionPixelSize(
R.styleable.PagerSlidingTabStrip_pstsUnderlineHeight,
underlineHeight);
dividerPadding = a.getDimensionPixelSize(
R.styleable.PagerSlidingTabStrip_pstsDividerPadding,
dividerPadding);
tabPadding = a.getDimensionPixelSize(
R.styleable.PagerSlidingTabStrip_pstsTabPaddingLeftRight,
tabPadding);
tabBackgroundResId = a.getResourceId(
R.styleable.PagerSlidingTabStrip_pstsTabBackground,
tabBackgroundResId);
shouldExpand = a
.getBoolean(R.styleable.PagerSlidingTabStrip_pstsShouldExpand,
shouldExpand);
scrollOffset = a
.getDimensionPixelSize(
R.styleable.PagerSlidingTabStrip_pstsScrollOffset,
scrollOffset);
textAllCaps = a.getBoolean(
R.styleable.PagerSlidingTabStrip_pstsTextAllCaps, textAllCaps);
a.recycle();
rectPaint = newPaint();
rectPaint.setAntiAlias(true);
rectPaint.setStyle(Style.FILL);
dividerPaint = newPaint();
dividerPaint.setAntiAlias(true);
dividerPaint.setStrokeWidth(dividerWidth);
defaultTabLayoutParams = newLinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
expandedTabLayoutParams = newLinearLayout.LayoutParams(0,
LayoutParams.MATCH_PARENT, 1.0f);
if (locale == null) {
locale = getResources().getConfiguration().locale;
}
}
publicvoidsetViewPager(ViewPager pager) {
this.pager = pager;
if (pager.getAdapter() == null) {
thrownewIllegalStateException(
"ViewPager does not have adapter instance.");
}
pager.setOnPageChangeListener(pageListener);
notifyDataSetChanged();
}
publicvoidsetOnPageChangeListener(OnPageChangeListener listener) {
this.delegatePageListener = listener;
}
publicvoidnotifyDataSetChanged() {
tabsContainer.removeAllViews();
tabCount = pager.getAdapter().getCount();
for (inti=0; i < tabCount; i++) {
if (pager.getAdapter() instanceof IconTabProvider) {
addIconTab(i,
((IconTabProvider) pager.getAdapter())
.getPageIconResId(i));
} else {
addTextTab(i, pager.getAdapter().getPageTitle(i).toString());
}
}
updateTabStyles();
getViewTreeObserver().addOnGlobalLayoutListener(
newOnGlobalLayoutListener() {
@SuppressWarnings("deprecation")@SuppressLint("NewApi")@OverridepublicvoidonGlobalLayout() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
getViewTreeObserver().removeGlobalOnLayoutListener(
this);
} else {
getViewTreeObserver().removeOnGlobalLayoutListener(
this);
}
currentPosition = pager.getCurrentItem();
tabsContainer.getChildAt(currentPosition).setSelected(
true);// Fix : ICON SELECTOR
scrollToChild(currentPosition, 0);
}
});
}
privatevoidaddTextTab(finalint position, String title) {
TextViewtab=newTextView(getContext());
tab.setText(title);
tab.setGravity(Gravity.CENTER);
tab.setSingleLine();
addTab(position, tab);
}
privatevoidaddIconTab(finalint position, int resId) {
ImageButtontab=newImageButton(getContext());
tab.setImageResource(resId);
addTab(position, tab);
}
privatevoidaddTab(finalint position, View tab) {
tab.setFocusable(true);
tab.setOnClickListener(newOnClickListener() {
@OverridepublicvoidonClick(View v) {
pager.setCurrentItem(position);
}
});
tab.setPadding(tabPadding, 0, tabPadding, 0);
tabsContainer
.addView(tab, position, shouldExpand ? expandedTabLayoutParams
: defaultTabLayoutParams);
}
privatevoidupdateTabStyles() {
for (inti=0; i < tabCount; i++) {
Viewv= tabsContainer.getChildAt(i);
v.setBackgroundResource(tabBackgroundResId);
if (v instanceof TextView) {
TextViewtab= (TextView) v;
tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, tabTextSize);
tab.setTypeface(tabTypeface, tabTypefaceStyle);
tab.setTextColor(tabTextColor);
// setAllCaps() is only available from API 14, so the upper case// is made manually if we are on a// pre-ICS-buildif (textAllCaps) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
tab.setAllCaps(true);
} else {
tab.setText(tab.getText().toString()
.toUpperCase(locale));
}
}
}
}
}
privatevoidscrollToChild(int position, int offset) {
if (tabCount == 0) {
return;
}
intnewScrollX= tabsContainer.getChildAt(position).getLeft() + offset;
if (position > 0 || offset > 0) {
newScrollX -= scrollOffset;
}
if (newScrollX != lastScrollX) {
lastScrollX = newScrollX;
scrollTo(newScrollX, 0);
}
}
@OverrideprotectedvoidonDraw(Canvas canvas) {
super.onDraw(canvas);
if (isInEditMode() || tabCount == 0) {
return;
}
finalintheight= getHeight();
// draw indicator line
rectPaint.setColor(indicatorColor);
// default: line below current tabViewcurrentTab= tabsContainer.getChildAt(currentPosition);
floatlineLeft= currentTab.getLeft();
floatlineRight= currentTab.getRight();
// if there is an offset, start interpolating left and right coordinates// between current and next tabif (currentPositionOffset > 0f && currentPosition < tabCount - 1) {
ViewnextTab= tabsContainer.getChildAt(currentPosition + 1);
finalfloatnextTabLeft= nextTab.getLeft();
finalfloatnextTabRight= nextTab.getRight();
lineLeft = (currentPositionOffset * nextTabLeft + (1f - currentPositionOffset)
* lineLeft);
lineRight = (currentPositionOffset * nextTabRight + (1f - currentPositionOffset)
* lineRight);
}
//SU TU002
canvas.drawRect(lineLeft, height - indicatorHeight, lineRight,height,
rectPaint);
// canvas.drawRect(lineLeft, 0, lineRight, indicatorHeight, rectPaint); // EU TU002// draw underline
rectPaint.setColor(underlineColor);
//SU TU002
canvas.drawRect(0, height - underlineHeight,tabsContainer.getWidth(),
height, rectPaint);
// canvas.drawRect(0, 0, tabsContainer.getWidth(), underlineHeight,// rectPaint); // EU TU002// draw divider
dividerPaint.setColor(dividerColor);
for (inti=0; i < tabCount - 1; i++) {
Viewtab= tabsContainer.getChildAt(i);
canvas.drawLine(tab.getRight(), dividerPadding, tab.getRight(),
height - dividerPadding, dividerPaint);
}
}
privateclassPageListenerimplementsOnPageChangeListener {
@OverridepublicvoidonPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
currentPosition = position;
currentPositionOffset = positionOffset;
scrollToChild(position, (int) (positionOffset * tabsContainer
.getChildAt(position).getWidth()));
invalidate();
if (delegatePageListener != null) {
delegatePageListener.onPageScrolled(position, positionOffset,
positionOffsetPixels);
}
}
@OverridepublicvoidonPageScrollStateChanged(int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
scrollToChild(pager.getCurrentItem(), 0);
}
if (delegatePageListener != null) {
delegatePageListener.onPageScrollStateChanged(state);
}
}
@OverridepublicvoidonPageSelected(int position) {
/**
* Fix : ICON SELECTOR
*/
tabsContainer.getChildAt(currentPageSelected).setSelected(false);
currentPageSelected = position;
tabsContainer.getChildAt(position).setSelected(true);
/**
* Fix : ICON SELECTOR
*/if (delegatePageListener != null) {
delegatePageListener.onPageSelected(position);
}
}
}
publicvoidsetIndicatorColor(int indicatorColor) {
this.indicatorColor = indicatorColor;
invalidate();
}
publicvoidsetIndicatorColorResource(int resId) {
this.indicatorColor = getResources().getColor(resId);
invalidate();
}
publicintgetIndicatorColor() {
returnthis.indicatorColor;
}
publicvoidsetIndicatorHeight(int indicatorLineHeightPx) {
this.indicatorHeight = indicatorLineHeightPx;
invalidate();
}
publicintgetIndicatorHeight() {
return indicatorHeight;
}
publicvoidsetUnderlineColor(int underlineColor) {
this.underlineColor = underlineColor;
invalidate();
}
publicvoidsetUnderlineColorResource(int resId) {
this.underlineColor = getResources().getColor(resId);
invalidate();
}
publicintgetUnderlineColor() {
return underlineColor;
}
publicvoidsetDividerColor(int dividerColor) {
this.dividerColor = dividerColor;
invalidate();
}
publicvoidsetDividerColorResource(int resId) {
this.dividerColor = getResources().getColor(resId);
invalidate();
}
publicintgetDividerColor() {
return dividerColor;
}
publicvoidsetUnderlineHeight(int underlineHeightPx) {
this.underlineHeight = underlineHeightPx;
invalidate();
}
publicintgetUnderlineHeight() {
return underlineHeight;
}
publicvoidsetDividerPadding(int dividerPaddingPx) {
this.dividerPadding = dividerPaddingPx;
invalidate();
}
publicintgetDividerPadding() {
return dividerPadding;
}
publicvoidsetScrollOffset(int scrollOffsetPx) {
this.scrollOffset = scrollOffsetPx;
invalidate();
}
publicintgetScrollOffset() {
return scrollOffset;
}
publicvoidsetShouldExpand(boolean shouldExpand) {
this.shouldExpand = shouldExpand;
requestLayout();
}
publicbooleangetShouldExpand() {
return shouldExpand;
}
publicbooleanisTextAllCaps() {
return textAllCaps;
}
publicvoidsetAllCaps(boolean textAllCaps) {
this.textAllCaps = textAllCaps;
}
publicvoidsetTextSize(int textSizePx) {
this.tabTextSize = textSizePx;
updateTabStyles();
}
publicintgetTextSize() {
return tabTextSize;
}
publicvoidsetTextColor(int textColor) {
this.tabTextColor = textColor;
updateTabStyles();
}
publicvoidsetTextColorResource(int resId) {
this.tabTextColor = getResources().getColor(resId);
updateTabStyles();
}
publicintgetTextColor() {
return tabTextColor;
}
publicvoidsetTypeface(Typeface typeface, int style) {
this.tabTypeface = typeface;
this.tabTypefaceStyle = style;
updateTabStyles();
}
publicvoidsetTabBackground(int resId) {
this.tabBackgroundResId = resId;
}
publicintgetTabBackground() {
return tabBackgroundResId;
}
publicvoidsetTabPaddingLeftRight(int paddingPx) {
this.tabPadding = paddingPx;
updateTabStyles();
}
publicintgetTabPaddingLeftRight() {
return tabPadding;
}
@OverridepublicvoidonRestoreInstanceState(Parcelable state) {
SavedStatesavedState= (SavedState) state;
super.onRestoreInstanceState(savedState.getSuperState());
currentPosition = savedState.currentPosition;
requestLayout();
}
@Overridepublic Parcelable onSaveInstanceState() {
ParcelablesuperState=super.onSaveInstanceState();
SavedStatesavedState=newSavedState(superState);
savedState.currentPosition = currentPosition;
return savedState;
}
staticclassSavedStateextendsBaseSavedState {
int currentPosition;
publicSavedState(Parcelable superState) {
super(superState);
}
privateSavedState(Parcel in) {
super(in);
currentPosition = in.readInt();
}
@OverridepublicvoidwriteToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(currentPosition);
}
publicstaticfinal Parcelable.Creator<SavedState> CREATOR = newParcelable.Creator<SavedState>() {
@Overridepublic SavedState createFromParcel(Parcel in) {
returnnewSavedState(in);
}
@Overridepublic SavedState[] newArray(int size) {
returnnewSavedState[size];
}
};
}
}
Your Activity Layout :
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"xmlns:app="http://schemas.android.com/apk/res-auto"android:layout_width="fill_parent"android:layout_height="fill_parent" ><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="match_parent" ><com.application.ui.view.PagerSlidingTabStripandroid:id="@+id/pager_sliding_tab_strip"android:layout_width="fill_parent"android:layout_height="48dip"android:layout_alignParentTop="true"android:background="@drawable/background_tabs"app:pstsIndicatorColor="@color/background_actionbar"app:pstsTabPaddingLeftRight="14dip" /><android.support.v4.view.ViewPagerandroid:id="@+id/pager"android:layout_width="fill_parent"android:layout_height="wrap_content"></android.support.v4.view.ViewPager></RelativeLayout></RelativeLayout>
Your Activity :
publicclassMotherActivityextendsActionBarActivity {
publicstaticfinalStringTAG= MotherActivity.class.getSimpleName();
private ViewPager mPager;
private PagerSlidingTabStrip mPagerSlidingTabStrp;
private ViewPager.SimpleOnPageChangeListener ViewPagerListener;
private ActionBar mActionBar;
protectedvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mother);
initUi();
setPagerSlidingTabStrip();
}
privatevoidinitUi() {
mPager = (ViewPager) findViewById(R.id.pager);
mPagerSlidingTabStrp = (PagerSlidingTabStrip) findViewById(R.id.pager_sliding_tab_strip);
}
privatevoidsetPagerSlidingTabStrip() {
ViewPagerAdapterviewpageradapter=newViewPagerAdapter(
getSupportFragmentManager());
mPager.setOffscreenPageLimit(5);
mPager.setAdapter(viewpageradapter);
mPagerSlidingTabStrp.setShouldExpand(true);
mPagerSlidingTabStrp.setViewPager(mPager);
}
}
ViewPagerAdapter
: which passes fragment on tab selection or swiping it. Pass on Fragment and drawables in here.
publicclassViewPagerAdapterextendsFragmentPagerAdapterimplementsIconTabProvider {
finalintPAGE_COUNT=5;
privatefinalint[] ICONS = { R.drawable.tab_icon_feed_home_selector,
R.drawable.tab_icon_feed_friends_selector, R.drawable.tab_icon_feed_popular_selector,
R.drawable.tab_icon_feed_report_selector, R.drawable.tab_icon_feed_report_selector };
publicViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Overridepublic Fragment getItem(int item) {
switch (item) {
case0:
FragmentAttendancefragmentAttendance=newFragmentAttendance();
return fragmentAttendance;
case1:
FragmentPremiumfragmentPremium=newFragmentPremium();
return fragmentPremium;
case2:
FragmentLeadfragmentLead=newFragmentLead();
return fragmentLead;
case3:
FragmentLeadfragmentLead=newFragmentLead();
return fragmentLead;
case4:
FragmentLeadfragmentLead=newFragmentLead();
return fragmentLead;
}
returnnull;
}
@OverridepublicintgetCount() {
// TODO Auto-generated method stubreturn PAGE_COUNT;
}
@OverridepublicintgetPageIconResId(int position) {
// TODO Auto-generated method stubreturn ICONS[position];
}
}
Solution 3:
Use the following code for changing the size of tab and making tabs fit within the screenwidth. Make sure your are using the Custom View
DisplayMetricsdisplaymetrics=newDisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
intscreenWidth= displaymetrics.widthPixels;
finalViewtabView= actionBar.getTabAt(0).getCustomView();
finalViewtabContainerView= (View) tabView.getParent();
finalinttabPadding= tabContainerView.getPaddingLeft() + tabContainerView.getPaddingRight();
finalinttabs= actionBar.getTabCount();
for(int i=0 ; i < tabs ; i++) {
Viewtab= actionBar.getTabAt(i).getCustomView();
LinearLayouttabItemLayout= (LinearLayout) tab.findViewById(R.id.tabItemLayout);
tabItemLayout.setLayoutParams(newLayoutParams(screenWidth/tabs-tabPadding-1, LayoutParams.WRAP_CONTENT));
}
Post a Comment for "Actionbar Tabs Set Dynamic Width According To Screen Width"