Remove BottomNavigationView Icons and center title - java

I have a bottom navigation view with 3 items. I want to only have centered text for each tab, and would therefore like to fully remove icons (not only make them transparent).
How can I remove Icons and center the titles?
This is what I have:
This is what I want:
My code: (Prefer solution in XML)
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_alignParentBottom="true">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/navigationBar"
android:background="#color/navigation"
app:theme="#style/BottomNavigationTheme"
app:menu="#menu/bottom_navigation_menu"
android:minHeight="#dimen/abc_action_bar_default_height_material">
</com.google.android.material.bottomnavigation.BottomNavigationView>
</RelativeLayout>
</merge>
bottom_navigation_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/ic_home"
android:title="#string/home">
</item>
<item
android:id="#+id/ic_today"
android:title="#string/today">
</item>
<item
android:id="#+id/ic_you"
android:title="#string/you">
</item>
</menu>

The easiest way is to just use
android:paddingBottom="16dp" //(any dp you want)
android:clipToPadding="false"

This works, for me
private int baselineHeight = 0;
private void removeIcons(BottomNavigationView view) {
BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0);
for (int i = 0; i < menuView.getChildCount(); i++) {
BottomNavigationItemView itemView = (BottomNavigationItemView) (menuView.getChildAt(i));
BaselineLayout baseline = (BaselineLayout) itemView.getChildAt(1);
FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) baseline.getLayoutParams();
baselineHeight = baselineHeight > 0 ? baselineHeight : (menuView.getHeight() + baseline.getHeight()) / 2;
layoutParams.height = baselineHeight;
baseline.setLayoutParams(layoutParams);
}
}
just call it in onCreate() in your Activity and pass your BottomNavigationView as parameter.
If you don't want to clutter your Activities or Fragments with excess code and you want this present in your layout XML you can create a custom View that extends BottomNavigationView and call this function in onLayout() override.

Add fix height to your bottom sheet and set bottom padding. Works for me.
android:layout_height="35dp"
android:paddingBottom="20dp"
android:clipToPadding="false"

you can use this property of bottom navigationview to hide the text and it will automatically centered your icons and i think ou do not use the minHeight property sir.
app:labelVisibilityMode="unlabeled"

Related

NavigationView menu items with actionLayout. How can I set those action layout's attribute for each item?

Following this answer, I learned how to add extra views to the NavigationView's menu items, by adding an action layout. My question is, esentially, how can I tweak each of those individual actionLayouts dinamically, through Java?
In my case, instead of adding a "switch" to the menu items, I used actionLayouts to add a extra icon, that will show a state for that item. It's a boolean state, so I want to show the difference either by changing the extra icon dinamically, or either toggling visibility.
So, I have a menu.xml like this one for my NavigationView:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:showIn="navigation_view">
<group android:id="#+id/menu_group"
android:checkableBehavior="single" >
<item
android:id="#+id/menu_item1"
android:icon="#drawable/some_main_icon"
app:actionLayout="#layout/myflag_actionlayout"
android:title="OPTION 1" />
<item
android:id="#+id/menu_item2"
android:icon="#drawable/some_main_icon"
app:actionLayout="#layout/myflag_actionlayout"
android:title="OPTION 2" />
<!-- etc. -->
</group>
</menu>
...and my myflag_actionlayout.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:background="#444444"
android:layout_width="wrap_content"
android:layout_height="match_parent">
<ImageView
android:id="#+id/lockedIcon"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:srcCompat="#android:drawable/ic_lock_idle_lock" />
</LinearLayout>
So, it looks like this more or less:
Now I wonder: how can I get each of those menu item's instances, access to their <ImageView> instance from Java and change each lockedIcon's ImageView depending on a boolean variable? (For instance, toggling the ImageView's visible attribute, or changing the image for app:srcCompat attribute) Should I use some findViewById(R.id.lockedIcon) for this task, or is it a bad idea and I should do it another way?
EDIT:
Just now I recall, I already did something similar to access those "NavigationView items" by Java, and add a string to the counter editing the title:
NavigationView nav_v = findViewById(R.id.navigation_view);
MenuItem nav_option1 = nav_v.getMenu().findItem(R.id.menu_item1);
nav_option1.setTitle(getString(R.string.nav_option1_title) + " -> " + some_counter);
Maybe i can from nav_option1 invoke some method to access it's action layout?
Good! #ianhanniballake 's suggested method worked like a charm. If I do this:
NavigationView nav_v = findViewById(R.id.navigation_view);
MenuItem nav_option1 = nav_v.getMenu().findItem(R.id.menu_item1);
ImageView option1_lock_icon = nav_option1.getActionView().findViewById(R.id.lockedIcon);
And from there, I could do whatever I want with this ImageView:
// Toggle visibility approach
if (item_locked) {
option1_lock_icon.setVisibility(View.VISIBLE);
} else {
option1_lock_icon.setVisibility(View.INVISIBLE);
}
// Change icon approach
string uri = "";
if (item_locked) {
uri = "#android:drawable/ic_lock_idle_lock";
} else {
uri = "#android:drawable/ic_menu_view";
}
int imageResource = getResources()
.getIdentifier(uri,
null,
getPackageName()
);
option1_lock_icon.setImageDrawable(
getResources().getDrawable(imageResource)
);
Also, it looks like I can do more or less the same with any object I add to those "action layouts". :-)

How to set a custom font to the title in toolbar android

I am doing this:
toolbar = (Toolbar) findViewById(com.sports.unity.R.id.tool_bar);
setSupportActionBar(toolbar);
setTitle("hello");
I want to set a custom font for the text here in the title "hello". How to do that?
Since android.support.v7.appcompat 24.2 Toolbar has method setTitleTextAppearance and you can set its font without external textview.
create new style in styles.xml
<style name="RobotoBoldTextAppearance">
<item name="android:fontFamily">#font/roboto_condensed_bold</item>
</style>
and use it
mToolbar.setTitleTextAppearance(this, R.style.RobotoBoldTextAppearance);
Update 2018 (kotlin version)
fun Toolbar.changeToolbarFont(){
for (i in 0 until childCount) {
val view = getChildAt(i)
if (view is TextView && view.text == title) {
view.typeface = Typeface.createFromAsset(view.context.assets, "fonts/customFont")
break
}
}
}
and use it like that toolBar.changeToolbarFont()
old-post
To use a custom title in your Toolbar all you need to do is remember is that Toolbar is just a fancy ViewGroup so you can add a custom title like so:
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_top"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="#color/action_bar_bkgnd"
app:theme="#style/ToolBarTheme" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toolbar Title"
android:layout_gravity="center"
android:id="#+id/toolbar_title" />
</android.support.v7.widget.Toolbar>
This means that you can style the TextView however you would like because it's just a regular TextView. So in your activity you can access the title like so:
Toolbar toolbarTop = (Toolbar) findViewById(R.id.toolbar_top);
TextView mTitle = (TextView) toolbarTop.findViewById(R.id.toolbar_title);
And then:
Typeface khandBold = Typeface.createFromAsset(BalrogApplication.getApplication().getAssets(), "fonts/Khand-bold.ttf");
mTitle.setTypeface(khandBold);
UPDATE
dynamically version
public static void changeToolbarFont(Toolbar toolbar, Activity context) {
for (int i = 0; i < toolbar.getChildCount(); i++) {
View view = toolbar.getChildAt(i);
if (view instanceof TextView) {
TextView tv = (TextView) view;
if (tv.getText().equals(toolbar.getTitle())) {
applyFont(tv, context);
break;
}
}
}
}
public static void applyFont(TextView tv, Activity context) {
tv.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/customFont"));
}
and use it like that
changeToolbarFont(findViewById(R.id.app_bar), this);
I still wanted to use the Toolbars title methods (nor did I want to have a custom Toolbar class), so adding in the custom TextView inside of the Toolbar xml element didn't work for me. Instead, I used the following method to find the TextView:
public static void applyFontForToolbarTitle(Activity context){
Toolbar toolbar = (Toolbar) context.findViewById(R.id.app_bar);
for(int i = 0; i < toolbar.getChildCount(); i++){
View view = toolbar.getChildAt(i);
if(view instanceof TextView){
TextView tv = (TextView) view;
Typeface titleFont = Typeface.
createFromAsset(context.getAssets(), "fonts/customFont");
if(tv.getText().equals(toolbar.getTitle())){
tv.setTypeface(titleFont);
break;
}
}
}
}
You can do this using just themes:
I wrote an article outlining the full solution. Here are the basics:
1) Define a theme in styles.xml:
<style name="ToolbarTheme" parent="ThemeOverlay.AppCompat.Light">
<item name="android:fontFamily">#font/fancy-font</item>
</style>
2) Set that theme in your Toolbars layout:
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:theme="#style/ToolbarTheme"/>
This assumes that you have a .ttf file stored in res/font:
You can create fonts folder under res directory in last version Android studio 3 .After this you must be define custom style in styles, and after this , you must be use titleTextAppearance in toolbar to style you are defined.
Steps like below.
1. Create fonts directory : res > Android Resource Directory > Resource type : fonts, and click on Ok to create fonts directory(Android studio 3).
Open styles.xml and make custom style like below
<style name="**TextAppearance.TabsFont**" parent="**android:TextAppearance**">
<item name="android:fontFamily">font/rmedium</item>
<item name="android:textSize">18sp</item>
</style>
3.Now open layout and add app:titleTextAppearance="#style/TextAppearance.TabsFont" to Toolbar tag, like below.
<android.support.v7.widget.Toolbar
android:id="#+id/toolbarMain"
app:title="#string/time_amp_date"
app:titleTextAppearance="#style/TextAppearance.TabsFont"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:theme="#style/AppTheme"
app:elevation="2dp" />
That's DONE. Now if you running app, you can see font set to your toolbar.
Placement of Fonts:
Firstly, download a .ttf file. My file is Balker.ttf
make sure that you have got an "assets" folder. If there is none, right click over app go to New>Folder>assets Folder
In assets folder, create a new folder and name it 'font'
Put your file, as I did with Balker.ttf, into the 'font' folder.
Go to the java file of the activity whose font you have to customize. I customized mainActivity here.
for(int i = 0; i < toolbar.getChildCount(); i++)
{ View view = toolbar.getChildAt(i);
if(view instanceof TextView) {
TextView textView = (TextView) view;
Typeface myCustomFont=Typeface.createFromAsset(getAssets(),"font/Balker.ttf");
textView.setTypeface(myCustomFont); }
}
Two way you can do custom font on toolbar title
Solution : 1 [ Static Method ]
1) Define a theme in styles.xml:
<style name="ToolbarTheme" parent="ThemeOverlay.AppCompat.Light">
<item name="android:fontFamily">#font/ubuntu</item>
</style>
2) Set that theme in your Toolbar's layout:
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:theme="#style/ToolbarTheme"/>
Solution 2 : [ Dynamic ]
Kotlin
fun Toolbar.titleFont(){
for (i in 0 until childCount) {
val view = getChildAt(i)
if (view is TextView && view.text == title) {
view.typeface = Typeface.createFromAsset(context.assets,"fonts/customfont.ttf")
break
}
}
}
then use it like
toolBar.titleFont()
You can use this simple method to set custom font to toolbar title.
Toolbar toolbar = (Toolbar) findViewById(com.sports.unity.R.id.tool_bar);
TextView tv = getToolBarTextView();
tv.settext("Hello");
private TextView getToolBarTextView() {
TextView titleTextView = null;
try {
Field f = mToolBar.getClass().getDeclaredField("mTitleTextView");
f.setAccessible(true);
titleTextView = (TextView) f.get(mToolBar);
Typeface font = Typeface.createFromAsset(getApplicationContext().getAssets(),"fonts/mfont.ttf");
titleTextView.setTypeface(font);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
return titleTextView;
}
No need to use external textview if you only want to change the font of toolbar title because android.support.v7.appcompat 24.2 Toolbar has method setTitleTextAppearance and you can set its font like below.
create a new style in styles.xml
<style name="CamptonBookTextAppearance">
<item name="android:fontFamily">#font/campton_book</item>
</style>
and use it
mToolbar.setTitleTextAppearance(this, R.style.CamptonBookTextAppearance);
This works for me
typeFace= Typeface.createFromAsset(this.getAssets(), "fonts/myfont.ttf");
((TextView)toolbar.getChildAt(1)).setTypeface(typeFace);
I searched for this question as well, and this was one of the first answers that came up. I'll add my solution since the one given here can be counted as a bit outdated (keep in mind it would work nonetheless).
Since Android now supports custom fonts, there's no reason to assign fonts in Java, it can be done while making the XML file itself.
First, in your layout file, add a custom Toolbar (you can set the text size here itself)
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_top"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="#color/primary">
<TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/signup"
android:textSize="22sp" />
</android.support.v7.widget.Toolbar>
Then, go to the design tab of your XML file, and select the text on the toolbar.
Select the option of fontFamily and select the font you want under the given options. If it is not given, you can search for more fonts.
Search for the font you want and select it. Your font gets changed.
Your XML file now will reflect the font you added, there will be an attribute named android:fontFamily
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_top"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="#color/primary">
<TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/roboto_slab"
android:text="#string/signup"
android:textColor="#color/secondaryBackground"
android:textSize="22sp" />
</android.support.v7.widget.Toolbar>
Hope this helped.
If anyone has an issue of getting multiple toolbar title (one default and one that you set ) for xml:
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:layout_gravity="left"
android:id="#+id/toolbar_title"
android:textSize="20sp"/>
</android.support.v7.widget.Toolbar>
then do this:
getSupportActionBar().setTitle(null);//Set the default to null
typeFace= Typeface.createFromAsset(getAssets(), "fonts/Raleway-Light.ttf");
toolbarTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
toolbarTitle.setTypeface(typeFace);
Just add textapperance in your toolbar xml no need to custumization:-
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:gravity="center"
android:minHeight="?attr/actionBarSize"
**app:titleTextAppearance="#font/montserrat_regular"**// apply your font
app:titleTextColor="#android:color/white" />
I made a binding adapter for this purpose.
public class FontBindingAdapter
{
#BindingAdapter({"font"})
public static void setFont(Toolbar toolbar, String font)
{
for (int i = 0; i < toolbar.getChildCount(); i++) {
if (toolbar.getChildAt(i) instanceof AppCompatTextView) {
UIUtil.setFont(font, (AppCompatTextView) toolbar.getChildAt(i));
}
}
}
}
Then use it like:
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/green"
app:font="#{`LatoRegular`}"
app:title="#string/setup_favorites"
app:titleTextColor="#color/white"/>
Thank you #gmetax, it's a good point. It's bad to access textview for each activity. We have to write code below for each activity:
TextView mTitle = (TextView) toolbarTop.findViewById(R.id.toolbar_title);
We've already bind toolbar and we've use toolbar.setTitle(). So, I extend Toolbar and override setTitle method like this:
#Override
public void setTitle(CharSequence title) {
super.setTitle("");
mTitle = (TextView) findViewById(R.id.toolbar_title);
if (mTitle != null) {
if (!TextUtils.isEmpty(title)) {
mTitle.setText(title);
}
}
}
(Of course, custom font should be setted in CustomTextView class.setTypeface)
Now, we can use just like this:
toolbar.setTitle("bla bla");
I still wanted to use the Toolbars title methods, so adding in the custom TextView inside of the Toolbar xml element didn't work for me. Instead, I used the following method to find the TextView:
public static void applyFontForToolbarTitle(Activity context){
Toolbar toolbar = (Toolbar) context.findViewById(R.id.app_bar);
for(int i = 0; i < toolbar.getChildCount(); i++){
View view = toolbar.getChildAt(i);
if(view instanceof TextView){
TextView tv = (TextView) view;
Typeface titleFont = Typeface.
createFromAsset(context.getAssets(), "fonts/customFont");
if(tv.getText().equals(context.getTitle())){
tv.setTypeface(titleFont);
break;
}
}
}
}
If you are using google fonts (ie. Open Sans) you can add TextView as a child of your Toolbar like this
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:fontFamily="#font/open_sans"/>
</android.support.v7.widget.Toolbar>
and then just set fontFamily property for your TextView in Attributes menu (More Fonts option at the end of the dropdown list)
android:fontFamily="#font/open_sans
You can Use Custom font of toolbar programmatically Like this
1) first Create sub dir fonts in asset folder
2) Add your font files in the fonts folder.
toolbar.setTitle("Welcome");
Typeface fromAsset = Typeface.createFromAsset(getAssets(),"fonts/OpenSans-Light.ttf");
((TextView)toolbar.getChildAt(1)).setTypeface(fromAsset);
1st create
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:titleTextAppearance="#style/DancingWhite"
app:popupTheme="#style/AppTheme.PopupOverlay"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toolbar Title"
android:layout_gravity="center"
android:id="#+id/toolbar_title" />
</android.support.v7.widget.Toolbar>
2nd
your activity you can access the title like so:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView mTitle = (TextView)
toolbar.findViewById(R.id.toolbar_title);
Typeface font = Typeface.createFromAsset(getAssets(), "Mukta- Regular.ttf");
mTitle.setTypeface(font);
just download what font you want to show in title and move it under res->font folder and create a file over there fontfamily
<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android">
<font
android:fontStyle="normal"
android:fontWeight="400"
android:font="#font/futura_book" />
<font
android:fontStyle="normal"
android:fontWeight="400"
android:font="#font/your font file name" />
</font-family>
now add fontfamily="your downloaded font family name like a.ttf" in your xml file thats it
Download the custom font and keep it in font folder inside the res folder.
As Toolbar is a viewGroup we can place the textView inside the Toolbar and use as follow
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:elevation="0dp">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
>
<TextView
android:id="#+id/toolbar_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Toolbar"
android:gravity="center"
android:fontFamily="#font/roboto_regular" <--- custom font
android:textColor="#color/white"
android:textStyle="bold"
android:textAppearance="#style/Base.TextAppearance.Widget.AppCompat.Toolbar.Title"
/>
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
This method is also used to make font BOLD.
I just add my fonts to the font folder I made in res along with the other fonts, then I made a custom XML file for the bar.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center">
<TextView
android:id="#+id/action_bar_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:textSize="30sp"
android:fontFamily="#font/yourfont"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"/></LinearLayout>
Then, I added this to my MainActivity
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setCustomView(R.layout.your_xml_file);
Both OTF and TTF works
The best answer really is the best. If you want to increase (adjust the font size) and change the colour then update your style like this:
<style name="NexaBoldToolbar">
<item name="android:fontFamily">#font/nexabold</item>
<item name="android:textSize">18sp</item>
<item name="android:textColor">#color/fullWhite</item>
</style>

How to change the text color of SlidingTabLayout?

I made an application which use the ActionBarCompat
I created the tabs using the SlidingTabLayout class.
the class is this:
SlidingTabLayout.java
but I can not change the color of the tabs...
my viewpager fragment is this:
<swmovil.fyb.SlidingTabLayout
android:id="#+id/mTabs"
android:layout_width="match_parent"
android:layout_height="48dip" />
<android.support.v4.view.ViewPager
android:id="#+id/mPager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1"
android:background="#color/white" />
the application works great, but i canĀ“t change the color text of the tabs...
I made the application after seeing the following example:
rudsonlive/Navigation-Drawer-ViewPager-ActionBarCompat
How can i change the text color of the tabs text ?
thanks !!!
1) First of all create color folder under res (/res/color)
2) create xml file selector.xml under /res/color folder
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:color="#android:color/white" />
<item android:state_focused="true" android:color="#android:color/white" />
<item android:state_pressed="true" android:color="#android:color/white" />
<item android:color="#504f4f" />
</selector>
3) Then in the populateTabStrip() method in SlidingTabLayout put this
tabTitleView.setTextColor(getResources().getColorStateList(R.color.selector));
now you have a selector and you can change the color of the text on any event you want
if that is not working add the following lines of code.
a) in populateTabStrip() method at the end add this
if (i == mViewPager.getCurrentItem()) {
tabView.setSelected(true);
}
and b) change the onPageSelected() method to this
#Override
public void onPageSelected(int position) {
if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
mTabStrip.onViewPagerPageChanged(position, 0f);
scrollToTab(position, 0);
}
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
mTabStrip.getChildAt(i).setSelected(position == i);
}
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageSelected(position);
}
}
Open your file SlidingTabLayout.java (the default one from Google IO) and find the function populateTabStrip() , then after this code
mTabStrip.addView(tabView);
if (i == mViewPager.getCurrentItem()) {
tabView.setSelected(true);
}
add the following line:
int color = ContextCompat.getColor(tabView.getContext(), R.color.grey);
tabTitleView.setTextColor(color);
Replace R.color.grey with your preferred color.
You should be able to see the TextView the class is using.
tabTitleView.setTextColor(getResources().getColor(R.color.white));
In my class, the TextView was tabTitleView. If you are using the default example provided by Google, you will find it under populateTabStrip function.
copy code of slidingtablayout and slidingtabstrip and put it in a java file.then make a customtab_title.xml in your layout folder and a selector.xml file in your drawable folder.
`
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp"
>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:textColor="#drawable/slidingtab_title_color"/>
</LinearLayout>
selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:color="#color/unpressed" />
<item android:state_focused="true" android:color="#color/unpressed" />
<item android:state_pressed="true" android:color="#color/unpressed" />
<item android:color="#android:color/black" />
</selector>
And in your mainactivity or where u r showing your tabs add one line of code - tabs.setCustomTabView(R.layout.customtab_title, R.id.textView2);
here tabs is slidingtablayout tabs;
to change indicator color add -
tabs.setSelectedIndicatorColors(getResources().getColor(R.color.unpressed));
#Override
public void onPageSelected(int position) {
for (int i = 0; i < mTabStrip.getChildCount(); i++) {
TextView tv = (TextView) mTabStrip.getChildAt(i);
if (i==position)
tv.setTextColor(getResources().getColorStateList(R.color.white));
else
tv.setTextColor(getResources().getColorStateList(R.color.tab_text_color));
}
this may be help you
Unfortunately this class doesn't support customizing the tab text color without editing the code and always uses the default text color of the theme. You'll have to patch the class to allow setting the tabs text color by code or by style attribute.
One alternative is to use the PagerSlidingTabStrip library.
Looking at the code for the SlidingTabLayout...You can set a custom tab view, which allows you to control the content of the tab and set a custom tab text color. Have a look at slidingTabLayout.setCustomTabView(int layoutResId, int textViewId).
I use Panayiotis Irakleous solution but I think it is better to avoid looping part in onPageSelected procedure.
The steps are the same, you need to add an int class member (example: mCurrentTabIndex) to save current tab index.
In steps 3.a, you need to add
mCurrentTabIndex = i;
So it will be like this:
if (i == mViewPager.getCurrentItem()) {
tabView.setSelected(true);
mCurrentTabIndex = i;
}
Last, in steps 3.b, replace the looping part to this:
mTabStrip.getChildAt(mCurrentTabIndex).setSelected(false);
mTabStrip.getChildAt(position).setSelected(true);
mCurrentTabIndex = position;
So the code will be like this:
#Override
public void onPageSelected(int position) {
if (mScrollState == ViewPager.SCROLL_STATE_IDLE) {
mTabStrip.onViewPagerPageChanged(position, 0f);
scrollToTab(position, 0);
}
mTabStrip.getChildAt(mCurrentTabIndex).setSelected(false);
mTabStrip.getChildAt(position).setSelected(true);
mCurrentTabIndex = position;
if (mViewPagerPageChangeListener != null) {
mViewPagerPageChangeListener.onPageSelected(position);
}
}

How to Set Background Color TabHost

I need help, I'm finding difficulty for change background color in a TabHost.
Original Image:
I need to modify background color like image below.
I tried many things in my code and XML too, but failed.
My code below:
TabHost tabHost = getTabHost();
// Tab 1
TabSpec aba1spec = tabHost.newTabSpec("Tab 1");
// setting Title and Icon for the Tab
tabHost.getTabWidget().setStripEnabled(false);
aba1spec.setIndicator("",getResources().getDrawable(R.drawable.tabenviaarq));
Intent photosIntent = new Intent(this, MainActivity.class);
aba1spec.setContent(photosIntent);
// Adding all TabSpec to TabHost
tabHost.addTab(aba1spec); // Adding tab1
in XML i have this:
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#android:id/tabs"
android:layout_alignParentTop="true"/>
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="65dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="-5dp"
android:background="#000000"/>
</RelativeLayout>
</TabHost>
Somebody have some idea i thanks a lot.
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
public void onTabChanged(String arg0) {
for (int i = 0; i < tab.getTabWidget().getChildCount(); i++) {
tab.getTabWidget().getChildAt(i)
.setBackgroundResource(R.drawable.tab_selected); // unselected
}
tab.getTabWidget().getChildAt(tab.getCurrentTab())
.setBackgroundResource(R.drawable.tab_unselected); // selected
}
});
Try this method, I hope this will help you.
Solution is to use background with selector, and the code is here:
private void initTabsAppearance(TabWidget tabWidget) {
// Change background
for(int i=0; i < tabWidget.getChildCount(); i++)
tabWidget.getChildAt(i).setBackgroundResource(R.drawable.tab_bg);
}
Where tab_bg is an xml drawable with selector:
For the full Tab customization I will add the code for changing tab text style using custom theme. Add this to styles.xml:
<style name="MyCustomTheme" parent="#android:style/Theme.Light.NoTitleBar">
<item name="android:tabWidgetStyle">#style/CustomTabWidget</item>
</style>
<style name="CustomTabWidget" parent="#android:style/Widget.TabWidget">
<item name="android:textAppearance">#style/CustomTabWidgetText</item>
</style>
<style name="CustomTabWidgetText" parent="#android:style/TextAppearance.Widget.TabWidget">
<item name="android:textSize">12sp</item>
<item name="android:textStyle">bold</item>
</style>
To use this theme, define it in AndroidManifest.xml:
<application android:theme="#style/MyCustomTheme">
And now you have tab widgets with custom background and custom text style.
I am solved exactly the same problem with this method:
private void setBackgroundColor() {
int inactiveColor = getResources().getColor(R.color.inactive_tab);
int activeColor = getResources().getColor(R.color.active_tab);
// In this loop you will set the inactive tabs backgroung color
for (int i = 0; i < tabWidget.getChildCount(); i++) {
tabWidget.getChildAt(i).setBackgroundColor(inactiveColor);
}
// Here you will set the active tab background color
tabWidget.getChildAt(tabHost.getCurrentTab()).setBackgroundColor(
activeColor);
}

Android: customizing the look of Tabs using TabHost & TabWidget

I opend a post about this before but I feel that I can now (after reading some other posts) better explain what I want and rephrase it so it will be better understand.
I followed the tutorial about Tab Layout on the dev guide and I managed to create tabs with it, but I want to do some customization to it (and I did look on other posts, but either the code had many mistakes to it or it didn't answer what I'm looking for).
The first problem I have is that the test is in most part over the icon instead of below it (I used an icon with dimensions 48x48 as recommended on the dev guide). I want the tab with to act like wrap_content does.
I also want to change the text size (I think it's called the label).
I want to use hex triplets to change the background color of the tabs, to change it between to situations : when this tab is the one selected and when it's not.
I want to be able to change the color of the line that is below the tabs, I could not find any information on how to do this.
The code I'm currently using to create a new tab is (from the dev guide):
intent = new Intent().setClass(this, GroupsActivity.class);
spec = tabHost.newTabSpec("groups").setIndicator("groups",
res.getDrawable(R.drawable.ic_tab_groups))
.setContent(intent);
tabHost.addTab(spec);
(groups is the tab name).
Help is very much appreciated!
Rather than trying to customize the widget tabs themselves, here is an alternate approach that I've used successfully on a project that may save you some headaches:
The idea is to use a hidden TabWidget in your layout and control it with a customized LinearLayout containing Buttons. This way, you can more easily customize the buttons to look however you'd like. You'll control the actual TabWidget in your Activity within each button's OnClick.
Create your layout with both the TabWidget and the Buttons:
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/tabhost" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:gravity="bottom">
<TabWidget android:id="#android:id/tabs"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:visibility="gone" />
<LinearLayout android:id="#+id/tabbar"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button android:id="#+id/firstButton"
android:layout_alignParentTop="true" android:background="#drawable/btn_first_on"
android:layout_width="100dp" android:layout_height="43dp"
android:clickable="true"></Button>
<Button android:id="#+id/secondButton"
android:layout_alignParentTop="true" android:background="#drawable/btn_second_off"
android:layout_height="43dp" android:layout_width="100dp"
android:clickable="true"></Button>
<Button android:id="#+id/thirdButton"
android:layout_alignParentTop="true" android:background="#drawable/btn_third_off"
android:layout_height="43dp" android:layout_width="100dp"
android:clickable="true"></Button>
<Button android:id="#+id/forthButton"
android:layout_alignParentTop="true" android:background="#drawable/btn_forth_off"
android:layout_height="43dp" android:layout_width="100dp"
android:clickable="true"></Button>
</LinearLayout>
<FrameLayout android:id="#android:id/tabcontent"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:layout_below="#+id/tabbar" />
</RelativeLayout>
</TabHost>
Set up the onCreate of your activity to handle using the buttons for adjusting the tab views:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// tabs
firstButton = (Button) findViewById(R.id.firstButton);
secondButton = (Button) findViewById(R.id.secondButton);
thirdButton = (Button) findViewById(R.id.thirdButton);
forthButton = (Button) findViewById(R.id.forthButton);
Resources res = getResources(); // Resource object to get Drawables
final TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Resusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
intent = new Intent().setClass(this, FirstGroupActivity.class);
spec = tabHost.newTabSpec("first").setIndicator("First").setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, SecondGroupActivity.class);
spec = tabHost.newTabSpec("second").setIndicator("Second").setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, ThirdGroupActivity.class);
spec = tabHost.newTabSpec("third").setIndicator("Third").setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, ForthActivity.class);
spec = tabHost.newTabSpec("forth").setIndicator("Forth").setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTab(0);
firstButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
tabHost.setCurrentTab(0);
firstButton.setBackgroundResource(R.drawable.btn_first_on);
secondButton.setBackgroundResource(R.drawable.btn_second_off);
thirdButton.setBackgroundResource(R.drawable.btn_third_off);
forthButton.setBackgroundResource(R.drawable.btn_forth_off);
}
});
secondButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
tabHost.setCurrentTab(1);
firstButton.setBackgroundResource(R.drawable.btn_first_off);
secondButton.setBackgroundResource(R.drawable.btn_second_on);
thirdButton.setBackgroundResource(R.drawable.btn_third_off);
forthButton.setBackgroundResource(R.drawable.btn_forth_off);
}
});
thirdButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
tabHost.setCurrentTab(3);
firstButton.setBackgroundResource(R.drawable.btn_first_off);
secondButton.setBackgroundResource(R.drawable.btn_second_off);
thirdButton.setBackgroundResource(R.drawable.btn_third_on);
forthButton.setBackgroundResource(R.drawable.btn_forth_off);
}
});
forthButton.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
tabHost.setCurrentTab(4);
firstButton.setBackgroundResource(R.drawable.btn_first_off);
secondButton.setBackgroundResource(R.drawable.btn_second_off);
thirdButton.setBackgroundResource(R.drawable.btn_third_off);
forthButton.setBackgroundResource(R.drawable.btn_forth_on);
}
});
}
As you can see, I'm using drawables for the images of the buttons on and off. Using this technique, you're not limited to the options available when simply just trying to customize the look of the TabWidget's tabs and you can create a completely custom look to your tabs.
1- Use a custom view:
spec = tabHost.newTabSpec("groups");
View view = LayoutInflater.from(this).inflate(R.layout.tabwidget_tabs, tabHost.getTabWidget(), false);
spec.setIndicator(view);
spec.setContent(intent);
instead of:
spec = tabHost.newTabSpec("groups").setIndicator("groups", res.getDrawable(R.drawable.ic_tab_groups)).setContent(intent);
tabHost.addTab(spec);
And then define the view for the tabs in the file tabwidget_tabs.xml (you can define an ImageView before the textView and the textsize):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/tabsLayout"
android:layout_width="wrap_content"
android:layout_height="34dp"
android:background="#drawable/tabs_bkgrd"
android:padding="5dp"
android:orientation="vertical">
<TextView android:id="#+id/tabsText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:textStyle="bold"
android:gravity="center_horizontal"
android:textSize="14dp" />
</LinearLayout>
2- It's not possible to use hex triplets to change the background color of the tabs because are drawables not colors. However you can use a selector that changes the drawables. and you can combine this solution with setColorFilter() and android:tint and then you can select the background using hex triplets: How to tint a bitmap
tabs_bkgrd.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Non focused states -->
<item android:state_focused="false" android:state_selected="false"
android:state_pressed="false" android:drawable="#drawable/tab_unselected_shape" />
<item android:state_focused="false" android:state_selected="true"
android:state_pressed="false" android:drawable="#drawable/tab_selected_shape" />
<!-- Focused states -->
<item android:state_focused="true" android:state_selected="false"
android:state_pressed="false" android:drawable="#drawable/tab_focused_shape" />
<item android:state_focused="true" android:state_selected="true"
android:state_pressed="false" android:drawable="#drawable/tab_focused_shape" />
<!-- Pressed -->
<item android:state_pressed="true" android:drawable="#drawable/tab_pressed_shape" />
</selector>
You can define a color or a shape, tab_selected_shape.xml:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient android:startColor="#color/gold1"
android:centerColor="#color/gold2"
android:endColor="#color/gold2"
android:angle="#integer/vertical_shape" />
</shape>
3- The line is a drawable too. you can find the files in the sdk and copy them into your project after modify them to change the color using gimp. You can combine this solution with setColorFilter() and android:tint and then you can select the background using hex triplets too. Read:
further explanation
android-sdk-linux_x86/platforms/android-7/data/res/drawable
tab_bottom_left.xml,
tab_bottom_right.xml,
tab_indicator.xml (define state changes)
android-sdk-linux_x86/platforms/android-7/data/res/drawable-mdpi
tab_focus.9.png (change color)
tab_focus_bar_left.9.png
tab_focus_bar_right.9.png
tab_press.9.png (change color)
tab_press_bar_left.9.png
tab_press_bar_right.9.png
tab_selected.9.png (change color)
tab_selected_bar_left.9.png tab_selected_bar_right.9.png
tab_unselected.9.png
What about the solution I proposed on this question?
You can customize the drawable of each button using the same used by native Android Tab bar(looking for resources in Android.jar to find the right drawables), plus you can customize additional behavious as you desire.
At the end, you will obtain something that is graphically similar to a tabbar, from an user perspective, but acts differently from a developer perspective.

Categories

Resources