How to customize tab bar with icons? - java

Can someone explain to me what I should add exactly to this code from this website:
III. To change tab icon use TabLayout.Tab#setIcon method. You can get TabLayout.Tab object via TabLayout#getTabAt method, which accept tab index as parameter.
...
//after initialization TabLayout and ViewPager
TabLayout.Tab tabCall = tabLayout.getTabAt(ITEM_CALL);
tabCall.setIcon(R.drawable.selector_call);
//repeat this code for all your tabs
...
Because I get tabLayout and ITEM_CALL in red!

You need to first create the selector xml files, and place them in your drawable folder, and those selector files need to reference valid drawables for the selected and non-selected states.
Then, just set the tab icons in onCreate() of the Activity.
Here is what your Activity should look like in order to show three tabs, with each tab showing only an icon:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setAdapter(new TabPagerAdapter(getSupportFragmentManager()));
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
TabLayout.Tab tabCall = tabLayout.getTabAt(0);
tabCall.setIcon(R.drawable.selector_call);
TabLayout.Tab tabHeart = tabLayout.getTabAt(1);
tabHeart.setIcon(R.drawable.selector_heart);
TabLayout.Tab tabContacts = tabLayout.getTabAt(2);
tabContacts.setIcon(R.drawable.selector_contacts);
}
class TabPagerAdapter extends FragmentPagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 3;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new CallFragment();
case 1:
return new HeartFragment();
case 2:
return new ContactsFragment();
}
return null;
}
}
}
Each tab needs its own selector xml file, here is an example of what the selector for the third tab should look like:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="true"
android:drawable="#drawable/contacts_selected" />
<item
android:state_selected="false"
android:drawable="#drawable/contacts_unselected" />
</selector>

declare this as a constant in your MainActivity class
private static final Striing ITEM_CALL = 0;
do this declaration on your onCreate() :
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
then create selector_call.xml in the drawable folder with this code :
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="true"
android:drawable="#drawable/ic_call_selected" />
<item
android:state_selected="false"
android:drawable="#drawable/ic_call_unselected" />
</selector>

<?xml version="1.0" encoding="utf-8"?>
<!-- coordinate layout add more than one widget in systematic way and
inhance others property-->
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Tab_Bar">
<!--Add space for toolbar and tab bars-->
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<!-- "?attr/actionBarSize" means same size as
original Toolbar size
"scroll|enterAlways" here "scroll" means when
we scroll viewPager up it is scrolled up and "enterAlways" means when
we scroll up it reappears -->
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<!--tabGravity="fill", if you want the tabs to be occupied the
fullwidth of the screen
If you want to keep your tabs horizontally centered, assign
tabGravity="center"
app:tabMode=> Defines the mode of the tab layout.
In our case the value should be “fixed” as we have limited number of
tabs but if you have many number of tabs where there is insufficient
space on the screen to fit all of them the you can change the
app:tabMode to "scrollable".-->
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabIndicatorColor="#F4F7FA"
app:tabGravity="fill">
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="One"
android:icon="#drawable/one_img"/>
<com.google.android.material.tabs.TabItem
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Two"
android:icon="#drawable/two_img"/>
</com.google.android.material.tabs.TabLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>

Related

Custom TabLayout Indicator - Android

I have been trying to make a custom TabLayout indicator like Google Drive's one but didn't figure it out.
I tried the following article:
https://medium.com/#adrianespi94/apply-new-google-style-to-your-android-material-tabs-4d498c993c51
It works fine, but not as good as the one in the GIF below.
Thanks in advance.
There's two thing like this.
works by clicking on tab.
works by horizontal scrolling and clicking on tab also.
I don't know what you want actually. cause, the link you gave that is no 1. which is TabHost. I am adding source code for both.
ViewPagerAdapter :
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList=new ArrayList<>();
private final List<String> fragmentListTitles=new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentListTitles.size();
}
//return page title
#Override
public CharSequence getPageTitle(int position) {
return fragmentListTitles.get(position);
}
public void AddFragment(Fragment fragment,String title)
{
fragmentList.add(fragment);
fragmentListTitles.add(title);
}
}
MainActivity :
private TabLayout tabLayout;
private AppBarLayout appBarLayout;
private ViewPager viewPager;
tabLayout=(TabLayout)findViewById(R.id.tablayout);
viewPager=(ViewPager)findViewById(R.id.viewpager);
//create viewpageradaper class object
ViewPagerAdapter adapter=new ViewPagerAdapter(getSupportFragmentManager());
//adding fragments using adapter object
adapter.AddFragment(new FreeFireFragment(), "Free Fire");
adapter.AddFragment(new PubgFragment(), "Pubg");
adapter.AddFragment(new CallOfDutyFragment(), "Call of Duty");
//set adapter into viewpager
viewPager.setAdapter(adapter);
//set viewpager into tablayout
tabLayout.setupWithViewPager(viewPager);
If you want to add icon :
//for set icon into tab items
final int[] ICONS = new int[]{
R.drawable.ff,
R.drawable.pubg,
R.drawable.cod
};
//enter the following source code below the MainActivity source code
//set icon to tab items
tabLayout.getTabAt(0).setIcon(ICONS[0]);
tabLayout.getTabAt(1).setIcon(ICONS[1]);
tabLayout.getTabAt(2).setIcon(ICONS[2]);
activity_home.xml :
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:id="#+id/tablayout"
android:layout_width="match_parent"
android:layout_height="55dp"
app:tabBackground="#color/homeColor"
app:tabGravity="fill"
app:tabIndicatorColor="#color/tabIndicator"
app:tabMode="fixed"
app:tabSelectedTextColor="#color/tabIndicator"
app:tabTextColor="#color/tabTextColor">
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/viewpager">
</androidx.viewpager.widget.ViewPager>
</LinearLayout>
Above source code works as no 2.
Now, no 1:
Layout :
<TabHost
android:id="#+id/tab_host"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#id/rl_">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/Filters"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
layout="#layout/filters_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:id="#+id/Adjustments"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
layout="#layout/adjustment_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</FrameLayout>
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#40cccccc" />
</LinearLayout>
</TabHost>
MainActivity
//setup tabHost
TabHost tabHost = findViewById(R.id.tab_host);
tabHost.setup();
//set item 1 in tabhost
TabHost.TabSpec Filters= tabHost.newTabSpec("Filters");
Filters.setContent(R.id.Filters);
Filters.setIndicator("Filters");
tabHost.addTab(Filters);
//set item 2 in tabhost
TabHost.TabSpec Adjustments= tabHost.newTabSpec("Adjustments");
Adjustments.setContent(R.id.Adjustments);
Adjustments.setIndicator("Adjustments");
tabHost.addTab(Adjustments);
I made the solution by myself, it seems like the solution can be done easily without libraries or any spaghetti code.
First, you need to an XML file for tab indicator:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners
android:bottomLeftRadius="0dp"
android:bottomRightRadius="0dp"
android:topLeftRadius="8dp"
android:topRightRadius="8dp" />
<size android:height="3dp" />
<solid android:color="#color/selectedColor" />
</shape>
Then make a Selector to change the indicator color based on your selection:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/selectedColor" android:state_selected="true" />
<item android:color="#color/notSelectedColor" />
</selector>
Finally in your TabLayout, add these lines:
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabIconTint="#drawable/tab_selector_color" //for selection
app:tabIndicator="#drawable/tab_indicator" //for rounded corners
app:tabIndicatorAnimationMode="elastic" //for that elastic swiping effect
app:tabIndicatorColor="#color/selectedColor"
app:tabIndicatorFullWidth="false"
app:tabInlineLabel="true"
app:tabSelectedTextColor="#color/selectedColor"
app:tabTextColor="#color/notSelectedColor"/>

Tablayout animation like whatsapp

I am using TabLayout and SearcView. How can I do , when click search button to hide tab layout like whatsapp.
I try setEnabled method but it can't work properly.
I also used Visibility,setActivated method.What can I do?I don't know. I must use setAnimation method or something else?
MainActivity.java
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private CoordinatorLayout coordinatorLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
coordinatorLayout = (CoordinatorLayout)findViewById(R.id.root_view);
toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = (ViewPager)findViewById(R.id.view_pager);
setUpViewPager(viewPager);
tabLayout = (TabLayout)findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private void setUpViewPager(ViewPager viewPager) {
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragment(CurrencyFragment.getInstance(),"Tracker"); // `CurrencyFragment.getInstance()` should be in `FragmentPagerAdapter.getItem()`
viewPagerAdapter.addFragment(ConvertFragment.getInstance(),"Converter"); // `ConvertFragment.getInstance()` should be in `FragmentPagerAdapter.getItem()`
viewPager.setAdapter(viewPagerAdapter);
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/root_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
app:titleTextColor="#android:color/white"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="fixed"
app:tabGravity="fill">
</android.support.design.widget.TabLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</android.support.design.widget.CoordinatorLayout>
If you have used menu item for search then you have to follow below code:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.search) // set your own id if you have different id from search.
{
tabLayout.setVisibility(View.GONE);
return true;
}
return super.onOptionsItemSelected(item);
}
When you finished with search then set tablayout visible.
tabLayout.setVisibility(View.VISIBLE);
Follow these simple steps
In your XML file create Appbar. Inside that create a Constraintlayout and keep it as match parent match parent.
Inside that keep your toolbar at the top and below that your tab layout.
Now Create the Edittext of search view as WhatsApp and keep it also as Top_to_top of parent and make the view View. Gone.
In Activity on click of the search icon
toolbar.setVisibility(View.GONE);
tabLayout.setVisibility(View.GONE);
searchViewEditText.setVisibility(View.GONE);

onNavigationItemSelected not being called for Bottom Navigation Bar

I'm trying to implement a bottom nav bar that changes fragments when the nav items are clicked. However, when I click on the nav bar items, the fragments don't change. Using log.d, I noticed onNavigationItemSelected is not being called. How do I fix this?
To note, the startFeedFragment, startScheduleFragment, & startSettingsFragmentare implemented the same way and they work for the buttons in the toolbar. I also referenced this tutorial and this question for help.
MainActivity.java
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
setUpRecycler();
startFeedFragment();
BottomNavigationView bottomNavBar = (BottomNavigationView) findViewById(R.id.navigation);
bottomNavBar.bringToFront();
bottomNavBar.setOnNavigationItemSelectedListener(this);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Log.d("NAV BAR", "onNavigationItemSelected hit");
switch (item.getItemId()) {
case R.id.feedMenu:
startFeedFragment();
Log.d("NAV BAR", "feed");
break;
case R.id.myScheduleMenu:
startScheduleFragment();
Log.d("NAV BAR", "schedule");
break;
case R.id.settingsMenu:
startSettingsFragment();
Log.d("NAV BAR", "settings lol");
break;
default:
Log.d("NAV BAR", "false");
return false;
}
return true;
}
/**
* Switches out the fragment for {#link FeedFragment} and sets an appropriate title. startScheduleFragmens & startSettingsFragment are implemented the same way
*/
private void startFeedFragment()
{
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragmentContainer, new FeedFragment());
transaction.commit();
getSupportActionBar().setTitle(R.string.title_fragment_feed);
}
}
Snippet from xml file
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<FrameLayout
android:id="#+id/fragmentContainer"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="#+id/navigation"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:itemBackground="#android:color/white"
app:itemIconTint="#color/colorPrimaryDark"
app:itemTextColor="#color/colorPrimaryDark"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:menu="#menu/bottom_nav"
android:elevation="8dp"/>
</android.support.constraint.ConstraintLayout>
</android.support.design.widget.CoordinatorLayout>
Solved! It was because I had set the buttons in the menu to android:enabled="false". That meant they couldn't be pressed, which is why onNavigationItemSelected wasn't being called. I set all buttons to android:enabled="true" to fix this.
Correct code for bottom_nav.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/bottom_nav_my_schedule"
android:title="#string/menu_my_schedule"
android:icon="#drawable/ic_event_available_white_24dp"
android:enabled="true"/> <!--make sure enabled is set to true!-->
<item android:id="#+id/bottom_nav_feed"
android:title="#string/menu_feed"
android:icon="#drawable/ic_view_list_white_24dp"
android:enabled="true" /> <!--make sure enabled is set to true!-->
<item android:id="#+id/bottom_nav_settings"
android:title="#string/menu_settings"
android:icon="#drawable/ic_settings_white_24dp"
android:enabled="true"/> <!--make sure enabled is set to true!-->
</menu>
As for me the problem was when my activity main layout was LinearLayout, so I've solved it by changing it to RelativeLayout, I have absolutely no thoughts why it's working, because RelativeLayout layouts reply only for elements location, not its view or something else, but it's working.
<RelativeLayout
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="match_parent"
android:orientation="vertical"
>
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<android.support.design.widget.BottomNavigationView
android:id="#+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:itemBackground="#drawable/selector"
android:background="#color/white"
app:menu="#menu/menu_bottom"
app:itemIconTint="#drawable/menu_trainings"
app:labelVisibilityMode="unlabeled"
/>
</RelativeLayout>

How to center title in Toolbar via java file? [duplicate]

I'm trying to figure out the right way to use a custom font for the toolbar title, and center it in the toolbar (client requirement).
At the moment, i'm using the good old ActionBar, and I was setting the title to empty value, and using setCustomView to put my custom font TextView and center it using ActionBar.LayoutParams.
Is there a better way to do that? Using the new Toolbar as my ActionBar.
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="?android: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);
This's just to help to join all pieces using #MrEngineer13 answer with #Jonik and #Rick Sanchez comments with the right order to help to achieve title centered easly!!
The layout with TextAppearance.AppCompat.Widget.ActionBar.Title :
<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:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/TextAppearance.AppCompat.Widget.ActionBar.Title"
android:layout_gravity="center" />
</android.support.v7.widget.Toolbar>
The way to achieve with the right order:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
mTitle.setText(toolbar.getTitle());
getSupportActionBar().setDisplayShowTitleEnabled(false);
Please don't forget to upvote #MrEngineer13 answer !!!
Here is a sample project ToolbarCenterTitleSample
Hope to help somebody else ;)
The ToolBar title is stylable. Any customization you make has to be made in the theme. I'll give you an example.
Toolbar layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
style="#style/ToolBarStyle.Event"
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="#dimen/abc_action_bar_default_height_material" />
Styles:
<style name="ToolBarStyle" parent="ToolBarStyle.Base"/>
<style name="ToolBarStyle.Base" parent="">
<item name="popupTheme">#style/ThemeOverlay.AppCompat.Light</item>
<item name="theme">#style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
</style>
<style name="ToolBarStyle.Event" parent="ToolBarStyle">
<item name="titleTextAppearance">#style/TextAppearance.Widget.Event.Toolbar.Title</item>
</style>
<style name="TextAppearance.Widget.Event.Toolbar.Title" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
<!--Any text styling can be done here-->
<item name="android:textStyle">normal</item>
<item name="android:textSize">#dimen/event_title_text_size</item>
</style>
we don't have direct access to the ToolBar title TextView so we use reflection to access it.
private TextView getActionBarTextView() {
TextView titleTextView = null;
try {
Field f = mToolBar.getClass().getDeclaredField("mTitleTextView");
f.setAccessible(true);
titleTextView = (TextView) f.get(mToolBar);
} catch (NoSuchFieldException e) {
} catch (IllegalAccessException e) {
}
return titleTextView;
}
Define the following class:
public class CenteredToolbar extends Toolbar {
private TextView centeredTitleTextView;
public CenteredToolbar(Context context) {
super(context);
}
public CenteredToolbar(Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
}
public CenteredToolbar(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
#Override
public void setTitle(#StringRes int resId) {
String s = getResources().getString(resId);
setTitle(s);
}
#Override
public void setTitle(CharSequence title) {
getCenteredTitleTextView().setText(title);
}
#Override
public CharSequence getTitle() {
return getCenteredTitleTextView().getText().toString();
}
public void setTypeface(Typeface font) {
getCenteredTitleTextView().setTypeface(font);
}
private TextView getCenteredTitleTextView() {
if (centeredTitleTextView == null) {
centeredTitleTextView = new TextView(getContext());
centeredTitleTextView.setTypeface(...);
centeredTitleTextView.setSingleLine();
centeredTitleTextView.setEllipsize(TextUtils.TruncateAt.END);
centeredTitleTextView.setGravity(Gravity.CENTER);
centeredTitleTextView.setTextAppearance(getContext(), R.style.TextAppearance_AppCompat_Widget_ActionBar_Title);
Toolbar.LayoutParams lp = new Toolbar.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER;
centeredTitleTextView.setLayoutParams(lp);
addView(centeredTitleTextView);
}
return centeredTitleTextView;
}
}
...and then just use it instead of regular Toolbar like this:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorAccent">
<your.packagename.here.CenteredToolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:title="#string/reset_password_page_title"/>
<!-- Other views -->
</RelativeLayout>
You still need these 2 lines of code in your Activity (as with standard Toolbar):
Toolbar toolbar = (Toolbar) findViewByid(R.id.toolbar); // note that your activity doesn't need to know that it is actually a custom Toolbar
setSupportActionBar(binding.toolbar);
That's it! You don't need to hide the standard left-aligned title, don't need to duplicate the same XML code over and over, etc., just use CenteredToolbar like if it was default Toolbar. You can also set your custom font programatically since you now have direct access to the TextView. Hope this helps.
MaterialToolbar from Material Components 1.4.0-alpha02 now has the ability to center the toolbar's title by setting the titleCentered attribute to true:
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.appbar.MaterialToolbar
android:id="#+id/topAppBar"
style="#style/Widget.MaterialComponents.Toolbar.Primary"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:titleCentered="true" />
</com.google.android.material.appbar.AppBarLayout>
Here is title text dependant approach to find TextView instance from Toolbar.
public static TextView getToolbarTitleView(ActionBarActivity activity, Toolbar toolbar){
ActionBar actionBar = activity.getSupportActionBar();
CharSequence actionbarTitle = null;
if(actionBar != null)
actionbarTitle = actionBar.getTitle();
actionbarTitle = TextUtils.isEmpty(actionbarTitle) ? toolbar.getTitle() : actionbarTitle;
if(TextUtils.isEmpty(actionbarTitle)) return null;
// can't find if title not set
for(int i= 0; i < toolbar.getChildCount(); i++){
View v = toolbar.getChildAt(i);
if(v != null && v instanceof TextView){
TextView t = (TextView) v;
CharSequence title = t.getText();
if(!TextUtils.isEmpty(title) && actionbarTitle.equals(title) && t.getId() == View.NO_ID){
//Toolbar does not assign id to views with layout params SYSTEM, hence getId() == View.NO_ID
//in same manner subtitle TextView can be obtained.
return t;
}
}
}
return null;
}
No one has mentioned this, but there are some attributes for Toolbar:
app:titleTextColor for setting the title text color
app:titleTextAppearance for setting the title text appearance
app:titleMargin for setting the margin
And there are other specific-side margins such as marginStart, etc.
I use this solution:
static void centerToolbarTitle(#NonNull final Toolbar toolbar) {
final CharSequence title = toolbar.getTitle();
final ArrayList<View> outViews = new ArrayList<>(1);
toolbar.findViewsWithText(outViews, title, View.FIND_VIEWS_WITH_TEXT);
if (!outViews.isEmpty()) {
final TextView titleView = (TextView) outViews.get(0);
titleView.setGravity(Gravity.CENTER);
final Toolbar.LayoutParams layoutParams = (Toolbar.LayoutParams) titleView.getLayoutParams();
layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
toolbar.requestLayout();
//also you can use titleView for changing font: titleView.setTypeface(Typeface);
}
}
Without toolbar TextView we can customize font by using below code
getSupportActionBar().setDisplayShowTitleEnabled(false);
or
getActionBar().setDisplayShowTitleEnabled(false);
public void updateActionbar(String title){
SpannableString spannableString = new SpannableString(title);
spannableString.setSpan(new TypefaceSpanString(this, "futurastdmedium.ttf"),
0, spannableString.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
mToolbar.setTitle(spannableString);
}
public class TestActivity extends AppCompatActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.activity_test);
toolbar = (Toolbar) findViewById(R.id.tool_bar); // Attaching the layout to the toolbar object
setSupportActionBar(toolbar);
customizeToolbar(toolbar);
}
public void customizeToolbar(Toolbar toolbar){
// Save current title and subtitle
final CharSequence originalTitle = toolbar.getTitle();
final CharSequence originalSubtitle = toolbar.getSubtitle();
// Temporarily modify title and subtitle to help detecting each
toolbar.setTitle("title");
toolbar.setSubtitle("subtitle");
for(int i = 0; i < toolbar.getChildCount(); i++){
View view = toolbar.getChildAt(i);
if(view instanceof TextView){
TextView textView = (TextView) view;
if(textView.getText().equals("title")){
// Customize title's TextView
Toolbar.LayoutParams params = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.MATCH_PARENT);
params.gravity = Gravity.CENTER_HORIZONTAL;
textView.setLayoutParams(params);
// Apply custom font using the Calligraphy library
Typeface typeface = TypefaceUtils.load(getAssets(), "fonts/myfont-1.otf");
textView.setTypeface(typeface);
} else if(textView.getText().equals("subtitle")){
// Customize subtitle's TextView
Toolbar.LayoutParams params = new Toolbar.LayoutParams(Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.MATCH_PARENT);
params.gravity = Gravity.CENTER_HORIZONTAL;
textView.setLayoutParams(params);
// Apply custom font using the Calligraphy library
Typeface typeface = TypefaceUtils.load(getAssets(), "fonts/myfont-2.otf");
textView.setTypeface(typeface);
}
}
}
// Restore title and subtitle
toolbar.setTitle(originalTitle);
toolbar.setSubtitle(originalSubtitle);
}
}
Layout:
<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="match_parent"
android:layout_height="wrap_content"
android:text="Toolbar Title"
android:layout_gravity="center"
android:gravity="center"
android:id="#+id/toolbar_title" />
</android.support.v7.widget.Toolbar>
Code:
Toolbar mToolbar = parent.findViewById(R.id.toolbar_top);
TextView mToolbarCustomTitle = parent.findViewById(R.id.toolbar_title);
//setup width of custom title to match in parent toolbar
mToolbar.postDelayed(new Runnable()
{
#Override
public void run ()
{
int maxWidth = mToolbar.getWidth();
int titleWidth = mToolbarCustomTitle.getWidth();
int iconWidth = maxWidth - titleWidth;
if (iconWidth > 0)
{
//icons (drawer, menu) are on left and right side
int width = maxWidth - iconWidth * 2;
mToolbarCustomTitle.setMinimumWidth(width);
mToolbarCustomTitle.getLayoutParams().width = width;
}
}
}, 0);
A very quick and easy way to set a custom font is to use a custom titleTextAppearance with a fontFamily:
Add to styles.xml:
<style name="ToolbarTitle" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
<item name="android:textSize">16sp</item>
<item name="android:textColor">#FF202230</item>
<item name="android:fontFamily">#font/varela_round_regular</item>
</style>
In your res folder create a font folder (Ex: varela_round_regular.ttf)
Read the official guide to find out more https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html
Solution that I used for this problem:
public static void applyFontForToolbarTitle(Activity a){
Toolbar toolbar = (Toolbar) a.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;
if(tv.getText().equals(a.getTitle())){
tv.setTypeface(getRuneTypefaceBold(a));
break;
}
}
}
}
For center gravity I think it would be necessary to change layout params to match_parent horizontally and then:
tv.setGravity(Gravity.CENTER);
I don't know if anything changed in the appcompat library but it's fairly trivial, no need for reflection.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// loop through all toolbar children right after setting support
// action bar because the text view has no id assigned
// also make sure that the activity has some title here
// because calling setText() with an empty string actually
// removes the text view from the toolbar
TextView toolbarTitle = null;
for (int i = 0; i < toolbar.getChildCount(); ++i) {
View child = toolbar.getChildAt(i);
// assuming that the title is the first instance of TextView
// you can also check if the title string matches
if (child instanceof TextView) {
toolbarTitle = (TextView)child;
break;
}
}
I solved this solution , And this is a following codes:
<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="Order History"
android:layout_gravity="center"
android:id="#+id/toolbar_title"
android:textSize="17sp"
android:textStyle="bold"
android:textColor="#color/colorWhite"
/>
</android.support.v7.widget.Toolbar>
And you can change title/label , in Activity, write a below codes:
Toolbar toolbarTop = (Toolbar) findViewById(R.id.toolbar_top);
TextView mTitle = (TextView) toolbarTop.findViewById(R.id.toolbar_title);
mTitle.setText("#string/....");
You can use like the following
<android.support.v7.widget.Toolbar
android:id="#+id/top_actionbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppThemeToolbar">
<TextView
android:id="#+id/pageTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
</android.support.v7.widget.Toolbar>
With the Material Components, starting from the version 1.4.x as described in the doc you can use the MaterialToolbar.
Just add the attribute app:titleCentered and/or app:subtitleCentered attributes to true on your MaterialToolbar.
Something like:
<com.google.android.material.appbar.MaterialToolbar
android:id="#+id/topAppBar"
app:titleCentered="true"
... />
With Compose using the Material3 package you can simply use the CenterAlignedTopAppBar:
CenterAlignedTopAppBar(
title = { Text("Centered TopAppBar") },
navigationIcon = {
IconButton(onClick = { /* doSomething() */ }) {
Icon(
imageVector = Icons.Filled.Menu,
contentDescription = "Localized description"
)
}
}
)
If you are using Compose and the Material2 package, there isn't a builtin component but you can customize the layout of content inside the TopAppBar as described in this answer.
Update from #MrEngineer13's answer: to align title center in any cases, including Hamburger icon, option menus, you can add a FrameLayout in toolbar like this:
<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" >
<FrameLayout android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toolbar Title"
android:layout_gravity="center"
style="#style/TextAppearance.AppCompat.Widget.ActionBar.Title"
android:id="#+id/toolbar_title" />
</FrameLayout>
</android.support.v7.widget.Toolbar>
Now using Material Design 3 we can align the title in the center without doing extra work or without adding a text view in the toolbar
Added below dependencies in build.gradle file
implementation 'com.google.android.material:material:1.6.1'
To align the title in the center We need to use the below properly
app:titleCentered="true"
To align subtitles in the center we need to use the below property
app:subtitleCentered="true"
Sample Code
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<com.google.android.material.appbar.MaterialToolbar
android:id="#+id/topAppBar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:title="AskNilesh"
app:subtitle="Nilesh"
app:subtitleCentered="true"
app:menu="#menu/top_app_bar"
app:titleCentered="true"
app:navigationIcon="#drawable/ic_android_black_24dp" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
OUTPUT
Even though adding a text view to the toolbar can solve the problem of the restriction of title styling, there is an issue with it. Since we are not adding it to a layout, we do not have too much control over its width. We can either use wrap_content or match_parent.
Now consider a scenario where we have a searchView as a button on the right edge of the toolbar. If the title contents are more, it will go on top of the button obscuring it. There is no way of controlling this short of setting a width to the label and is something you don't want to do if you want to have a responsive design.
So, here is a solution that worked for me which is slightly different from adding a textview to the toolbar. Instead of that, add the toolbar and text view to a relative layout and ensure that the text view is on top of the toolbar. Then we can use appropriate margins and make sure the text view shows up where we want it to show up.
Make sure you set the toolbar to not show the title.
Here is the XML for this solution:
<RelativeLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary">
<android.support.v7.widget.Toolbar
android:theme="#style/ThemeOverlay.AppCompat.Dark"
android:id="#+id/activity_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:titleTextAppearance="#style/AppTheme.TitleTextView"
android:layout_marginRight="40dp"
android:layoutMode="clipBounds">
<android.support.v7.widget.SearchView
android:id="#+id/search_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:foregroundTint="#color/white" />
</android.support.v7.widget.Toolbar>
<TextView
android:id="#+id/toolbar_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginRight="90dp"
android:text="#string/app_name"
android:textSize="#dimen/title_text_size"
android:textColor="#color/white"
android:lines="1"
android:layout_marginLeft="72dp"
android:layout_centerVertical="true" />
</RelativeLayout>
Solves the issue #ankur-chaudhary mentioned above.
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);
I spent several days searching for a universal solution. My toolbar working with android menu and nav icon.
At first, you need create custom toolbar class. This class must have calculate title centered positions (paddings):
class CenteredToolbar #JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
: Toolbar(context, attrs, defStyleAttr) {
init {
addOnLayoutChangeListener(object : View.OnLayoutChangeListener {
override fun onLayoutChange(v: View?, left: Int, top: Int, right: Int, bottom: Int, oldLeft: Int, oldTop: Int, oldRight: Int, oldBottom: Int) {
val titleTextView = findViewById<TextView>(R.id.centerTitle)
val x = titleTextView.x.toInt()
val x2 = x + titleTextView.width
val fullWidth = width
val fullCenter = fullWidth / 2
val offsetLeft = Math.abs(fullCenter - x)
val offsetRight = Math.abs(x2 - fullCenter)
val differOffset = Math.abs(offsetLeft - offsetRight)
if (offsetLeft > offsetRight) {
titleTextView.setPadding(differOffset, 0, 0, 0)
} else if (offsetRight > offsetLeft) {
titleTextView.setPadding(0, 0, differOffset, 0)
}
removeOnLayoutChangeListener(this)
}
})
}
override fun setTitle(resId: Int) = getTitleView().setText(resId)
override fun setTitle(title: CharSequence?) = getTitleView().setText(title)
fun getTitleView(): TextView = findViewById(R.id.centerTitle)
}
Secondly, you need create layout toolbar:
<CenteredToolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar">
<TextView
android:id="#+id/centerTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</CenteredToolbar>
That's all
Try taking Toolbar and tittle in a separate view. Take a view on right end and given them weight equal to the toolbar weight. In this way your tittle will come in center.
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
android:background="#color/white_color">
<LinearLayout
android:id="#+id/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/white_color">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="0dp"
android:layout_height="?attr/actionBarSize"
android:background="#color/white_color"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
android:layout_weight="0.2"
app:contentInsetStartWithNavigation="0dp"
app:navigationIcon="#color/greyTextColor">
</android.support.v7.widget.Toolbar>
<com.an.customfontview.CustomTextView
android:id="#+id/headingText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.6"
android:gravity="center"
android:text="Heading"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textColor="#color/colorPrimary"
android:textSize="#dimen/keyboard_number"
android:layout_gravity="center_horizontal|center_vertical"
app:textFontPath="fonts/regular.ttf" />
<ImageView
android:id="#+id/search_icon"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:visibility="visible"
android:layout_weight="0.2"
android:layout_gravity="center_horizontal|center_vertical"
android:src="#drawable/portfolio_icon"/>
</LinearLayout>
</android.support.design.widget.AppBarLayout>
You can insert this code in your xml file
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimaryDark"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toolbar Title"
android:textColor="#000000"
android:textSize="20dp"
android:id="#+id/toolbar_title" />
</androidx.appcompat.widget.Toolbar>
To use a custom title in your Toolbar you can add a custom title like :
<?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:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="5dp"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ThemeOverlay.AppCompat.Dark">
<LinearLayout
android:id="#+id/lnrTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/txvHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|center"
android:gravity="center"
android:ellipsize="end"
android:maxLines="1"
android:text="Header"
android:textColor="#color/white"
android:textSize="18sp" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
Java Code:
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() == null)
return;
getSupportActionBar().setTitle("Title");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Use com.google.android.material.appbar.MaterialToolbar and app:titleCentered="true" tag
<com.google.android.material.appbar.MaterialToolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:titleCentered="true" />
private void makeTitleCenter(String title, Toolbar toolbar) {
if (title != null && !TextUtils.isEmpty(title.trim())) {
final String tag = " ";
if (getSupportActionBar() != null) {
getSupportActionBar().setTitle(tag);
}
TextView titleTv = null;
View leftBtn = null;
for (int i = 0; i < toolbar.getChildCount(); i++) {
View view = toolbar.getChildAt(i);
CharSequence text = null;
if (view instanceof TextView && (text = ((TextView) view).getText()) != null && text.equals(tag)) {
titleTv = (TextView) view;
} else if (view instanceof ImageButton) {
leftBtn = view;
}
}
if (titleTv != null) {
final TextView fTitleTv = titleTv;
final View fLeftBtn = leftBtn;
fTitleTv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
fTitleTv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int leftWidgetWidth = fLeftBtn != null ? fLeftBtn.getWidth() : 0;
fTitleTv.setPadding(DimenUtil.getResources().getDisplayMetrics().widthPixels / 2 - leftWidgetWidth - fTitleTv.getWidth() / 2, 0, 0, 0);
fTitleTv.requestLayout();
}
});
}
}
}
for custom font in toolbar you can override textView font in style and then every textView in your app also toolbar title font changed automatically
i tested it in android studio 3.1.3
in style do it:
<style name="defaultTextViewStyle" parent="android:Widget.TextView">
<item name="android:fontFamily">#font/your_custom_font</item>
</style>
and then in your theme use this:
<item name="android:textViewStyle">#style/defaultTextViewStyle</item>
I found another way to add custom toolbar without any adicional Java/Kotlin code.
First: create a XML with your custom toolbar layout with AppBarLayout as the parent:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
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:theme="#style/AppTheme.AppBarOverlay">
<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">
<ImageView
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginEnd="#dimen/magin_default"
android:src="#drawable/logo" />
</android.support.v7.widget.Toolbar>
Second: Include the toolbar in your layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/blue"
tools:context=".app.MainAcitivity"
tools:layout_editor_absoluteY="81dp">
<include
layout="#layout/toolbar_inicio"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!-- Put your layout here -->
</android.support.constraint.ConstraintLayout>

Android remove actionbar title keeping toolbar menu

I need to keep my tabbed toolbar in my application removing the actionbar. This is how it looks like now:
But I want it to look like this:
My code xml is:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"/>
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
This is my .java:
public class MyActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
if (toolbar != null) {
setSupportActionBar(toolbar);
}
viewPager.setAdapter(new SectionPagerAdapter(getSupportFragmentManager()));
tabLayout.setupWithViewPager(viewPager);
}
public class SectionPagerAdapter extends FragmentPagerAdapter {
public SectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new myFragment1();
case 1:
default:
return new myFragment2();
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "myfragment1";
case 1:
default:
return "myfragment2";
}
}
}
}
How can I achieve it?
Thanks in advice
Simply add this in your MainActivity this will hide the text of your toolbar
getSupportActionBar().setTitle("");
To remove the toolbar you can set it's visibility to gone like
android:visibility="gone"
Here are your options:
1. It looks like you don't need Toolbar here at all. You can remove it from your xml file and add this line
getSupportActionBar().hide();
to your MyActivity.java instead of
if (toolbar != null) {
setSupportActionBar(toolbar);
}
2. If you want to keep the Toolbar in case of using it later, you can hide it in either xml file
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="gone"
android:background="?attr/colorPrimary"/>
or in your MyActivity.java after setting Toolbar as support action bar
if (toolbar != null) {
setSupportActionBar(toolbar);
}
toolbar.setVisibility(View.GONE);
Add following code to disable actionbar and enable toolbar in following files :-
Add this code to styles.xml
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="android:windowNoTitle">true</item>
<item name="android:windowActionBar">false</item>
</style>
for custom toolbar create layout/toolbar.xml
<ImageView
android:id="#+id/backButton"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginLeft="16dp"
android:background="#drawable/back"
android:padding="24dp"
android:visibility="gone" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:id="#+id/toolbarText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:textColor="#color/white" />
</LinearLayout>
in layout/activity.xml
<include
android:id="#+id/mallToolbar"
layout="#layout/toolbar" />
in MainActivity.java Add:-
toolbar = (Toolbar) findViewById(R.id.mallToolbar);
setSupportActionBar(toolbar);
Now you have added a custom toolbar to your android activity.

Categories