I have the following XML layout
<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=".MainActivity">
<FrameLayout
android:id="#+id/fragment_content"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.bottomappbar.BottomAppBar
android:id="#+id/bottomAppBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:fabCradleMargin="20dp"
app:fabCradleVerticalOffset="10dp"
app:fabCradleRoundedCornerRadius="20dp"
android:layout_gravity="bottom">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottomNavigationView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginEnd="16dp"
android:background="#android:color/transparent"
app:menu="#menu/bottom_nav_menu" />
</com.google.android.material.bottomappbar.BottomAppBar>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_anchor="#id/bottomAppBar" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
The associated Java file is the following:
public class MainActivity extends AppCompatActivity {
BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNavigationView = findViewById(R.id.bottomNavigationView);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Here's a Snackbar", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
My question is, I would like to assign an image source dynamically as well as an action based on which of the navigation fragment the user is on.
So when the app opens it would default to the fab button having a '+' which allows users to add items to list.
If they hit the setting nav button I would like for the image to be gear and if pressed it opens the user setting prefs.
I am just not sure how to achieve this?
UPDATE:
if (bottomNavigationView.getMenu().findItem(R.id.miHome).isChecked()) {
// Set icon image for FAB
fab.setImageResource(R.drawable.ic_add);
} else if (bottomNavigationView.getMenu().findItem(R.id.miSettings).isChecked()) {
fab.setImageResource(R.drawable.ic_settings);
fab.setBackgroundColor(Color.RED);
}
The behavior is that it will show the + sign on load, since the dashboard is the default at app launch, but when I hit the settings nav button, the FAB icon does NOT change to the gear and the background color does NOT turn red!?
Can anyone advise what I am doing wrong?
Using if (bottomNavigationView.getMenu().findItem(R.id.miHome).isChecked()) condition will be triggered only once, but you need to register a listener to the lifetime of the lifecycle owner of the bottomNavigationView which is the MainActivity.
This is typically the OnNavigationItemSelectedListener
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.miHome) {
fab.setImageResource(R.drawable.ic_add);
} else if (item.getItemId() == R.id.miSettings) {
fab.setImageResource(R.drawable.ic_settings);
fab.setBackgroundColor(Color.RED);
}
return true;
}
});
Please help with this, I've been going around in circles for hours!
I have a navigation drawer set up and a toolbar (see code below)
I CAN NOT get the back/home function to work, as clicking it results in opening the drawer.
This is in my MainActivity, called during OnCreate.
private fun initialiseViews() {
// Initialise the action bar as the XML toolbar, and set the Title as Dashboard
setSupportActionBar(toolbar)
supportActionBar!!.title = "Dashboard"
// Set-up the NavigationView and its listener
nav_view.setNavigationItemSelectedListener(this)
// Sets the hamburger toggle and its actions for the toolbar
val toggle = ActionBarDrawerToggle(
this, //host activity
drawer_layout, //Drawer Layout object
toolbar, // Toolbar Object
R.string.nav_open, //description for accessibility
R.string.nav_closed //description for accessibility
)
// Set the sync-state and draw-listener to the toggle (hamburger)
drawer_layout.addDrawerListener(toggle)
toggle.syncState()
}
The following is within the OnCreateView method of my fragments...
(activity as AppCompatActivity).supportActionBar!!.title = "About"
(activity as MainActivity).supportActionBar!!.setHomeButtonEnabled(true)
(activity as MainActivity).supportActionBar!!.setDisplayHomeAsUpEnabled(true)
The navigation drawer works fine. Changing the title of my toolbar works fine. The hamburger icon is changed to a back arrow within the fragment just fine...
However, each time I press the back arrow, it opens the drawer... kind of as if a listener for the drawer is above the back arrow...
Implementing any code within OnOptionsItemSelected results in nothing as no call is made to that method, since it just opens the drawer.
Would really appreciate someone to point out the obvious in what I have done wrong.
Thanks.
EDIT
main_activity.xml as requested to view...
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:background="#drawable/background_graphic">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:background="#color/colorLightOrange"
android:theme="#style/Theme.AppCompat.Light.DarkActionBar"
app:menu="#menu/toolbar_list_menu"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<android.support.design.widget.BottomNavigationView
android:id="#+id/not needed for post" />
<android.support.v4.view.ViewPager
android:id="#+id/not needed for post" />
</FrameLayout>
<!-- Navigation Drawer -->
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header"
app:menu="#menu/navigation_menu" />
Did you try to use something like this to set it like back button?
(activity as MainActivity).supportActionBar!!.setNavigationIcon(R.drawable.back)
(activity as MainActivity).supportActionBar!!.setNavigationOnClickListener {
(activity as MainActivity).supportActionBar!!.onBackPressed()
}
And override your onBackPressed
#Override
public void onBackPressed() {
if (sendBackPressToDrawer()) {
return;
}
if (sendBackPressToFragmentOnTop()) {
return;
}
super.onBackPressed();
if (fragmentManager.getBackStackEntryCount() > 0) {
return;
}
finish();
}
I want to go from fragment to activity using back button using toolbar back icon.
The fragment is my navigation drawer item & activity is my MainActivity.
How do I do it?
You can use app:navigationIcon="?attr/homeAsUpIndicator" for that back navigation icon.
<android.support.v7.widget.Toolbar
android:id="#+id/toolbarId"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:navigationIcon="?attr/homeAsUpIndicator"/>
For navigation:
Toolbar toolbar = (ToolBar) getActivity().findViewById(R.id.toolbarId);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().onBackPressed();
}
});
Call this method in your fragment onCreateView
public void showBackButton() {
if (getActivity() instanceof ActionBarActivity) {
((ActionBarActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
Try this worked for me :
in XML:
<android.support.v7.widget.Toolbar
android:id="#+id/profileToolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
Create an back arrow icon in drawable folder. Name it 'ic_back_button'.
Not sure how :-
just right click on drawable > new > ImageAsset > Clip Art > Search back > select > OK > Finish (don't forget to change the name).
then Inside your fragment in onCreateView :
Toolbar toolbar = view.findViewById(R.id.profileToolbar);
toolbar.setNavigationIcon(R.drawable.ic_back_button);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().onBackPressed();
}
});
It might help in case if you want to come back from fragment to previous location.
Put this in your class with navController.
#Override
public boolean onSupportNavigateUp() {
navController.navigateUp();
return super.onSupportNavigateUp();
}
don't forget implement relevant dependency such as navigation and navigation UI.
Add this xml code to your fragment and try
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#FFFFFF"
android:layout_gravity="center"
android:gravity="center_horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title Here"
android:typeface="serif"
android:layout_gravity="center"
android:id="#+id/toolbar_title"
android:textSize="20sp"
android:textColor="#android:color/black"/>
<ImageView
android:id="#+id/ivback_water"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:padding="15dp"
android:scaleType="fitCenter"
android:layout_gravity="left"
android:background="#drawable/ic_arrow_back_black_24dp" />
</android.support.v7.widget.Toolbar>
You can easily do that, if you are using a Custom back button that is placed on your Custom top app bar, in the button's onClick() function you can call.. getActivity().onBackPressed();
it would work the same as if you have clicked the android navigation's back button...
I have a quite simple layout and I animate the showing/hiding of the toolbars with the appended functions. I'm using AppCompat and Toolbars...
PROBLEM
One person reported that the top toolbar is never shown. Any ideas why? What could be the reason? It's working fine on my phone and others...
Function
public void showHideToolbar(boolean forceHide, boolean animate)
{
L.d(this, "showHideToolbar: " + mShowToolbar);
toolbar.clearAnimation();
toolbar2.clearAnimation();
if (mShowToolbar || forceHide)
{
if (animate) {
toolbar.animate().translationY(-toolbar.getBottom()).setInterpolator(new AccelerateInterpolator()).start();
toolbar2.animate().translationY(toolbar2.getBottom()).setInterpolator(new AccelerateInterpolator()).start();
}
else
{
toolbar.setTranslationY(-toolbar.getBottom());
toolbar2.setTranslationY(toolbar2.getBottom());
}
mShowToolbar = false;
}
else
{
if (animate) {
toolbar.animate().translationY(0).setInterpolator(new DecelerateInterpolator()).start();
toolbar2.animate().translationY(0).setInterpolator(new DecelerateInterpolator()).start();
}
else
{
toolbar.setTranslationY(0);
toolbar2.setTranslationY(0);
}
mShowToolbar = true;
}
}
Layout
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/flMain"
android:background="?attr/main_background_color"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
app:theme="?actionBarThemeStyle"
app:popupTheme="?actionBarPopupThemeStyle" />
<android.support.v4.view
android:id="#+id/vpSlides"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar2"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/bottom_bar_background"
android:elevation="0dp"
android:layout_alignParentBottom="true"
android:gravity="top|start"
app:theme="?actionBarThemeStyle"
app:popupTheme="?actionBarPopupThemeStyle" >
</android.support.v7.widget.Toolbar>
</RelativeLayout>
It seems like, even if you make a toolbar to an actionbar, you have to respect layout ordering in the xml. setSupportActionBar won't bring the action bar on top of the main layout...
So the simple solution was to reorder the toolbar to being under the content...
I never ad problems yet as normally I show the content underneath the toolbar, here I didn't want to that and therefore faced the problem
I'm trying to create simple application using android-support-v7:21 library.
Code snippets:
MainActivity.java
public class MainActivity extends ActionBarActivity {
Toolbar mActionBarToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
mActionBarToolbar.setTitle("My title");
setSupportActionBar(mActionBarToolbar);
}
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_actionbar"
android:background="#null"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:fitsSystemWindows="true" />
</LinearLayout>
But instead of "My title" on Toolbar %application name% is shown.
Seems like setTitle method has no effect.
I would like to show "My title".
UPD:
Before, styles.xml was:
<style name="AppTheme" parent="Theme.AppCompat">
<item name="windowActionBar">false</item>
</style>
So, I thought that actionbar is not used.
I add NoActionBar to style parent:
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
<item name="windowActionBar">false</item>
</style>
But the problem is not resolved.
Found the solution:
Instead of:
mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
mActionBarToolbar.setTitle("My title");
setSupportActionBar(mActionBarToolbar);
I used:
mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mActionBarToolbar);
getSupportActionBar().setTitle("My title");
And it works.
For anyone who needs to set up the title through the Toolbar some time after setting the SupportActionBar, read this.
The internal implementation of the support library just checks if the Toolbar has a title (not null) at the moment the SupportActionBar is set up. If there is, then this title will be used instead of the window title. You can then set a dummy title while you load the real title.
mActionBarToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
mActionBarToolbar.setTitle("");
setSupportActionBar(mActionBarToolbar);
later...
mActionBarToolbar.setTitle(title);
The above answer is totally true but not working for me.
I solved my problem with the following things.
Actually My XML is like that:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/confirm_order_mail_layout"
android:layout_width="match_parent"
android:layout_height="fill_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/confirm_order_appbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/confirm_order_list_collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp"
app:layout_scrollFlags="scroll|enterAlways">
<android.support.v7.widget.Toolbar
android:id="#+id/confirm_order_toolbar_layout"
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.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
I have tried all the option and after all I just removed CollapsingToolbarLayout because of i do not need to use in that particular XML So My Final XML is like:
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/confirm_order_mail_layout"
android:layout_width="match_parent"
android:layout_height="fill_parent">
<android.support.design.widget.AppBarLayout
android:id="#+id/confirm_order_appbar_layout"
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/confirm_order_toolbar_layout"
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.AppBarLayout>
</android.support.design.widget.CoordinatorLayout>
Now you have to use setTitle() like above answer:
mActionBarToolbar = (Toolbar) findViewById(R.id.confirm_order_toolbar_layout);
setSupportActionBar(mActionBarToolbar);
getSupportActionBar().setTitle("My Title");
Now If you want to use CollapsingToolbarLayout and Toolbar together then you have to use setTitle() of CollapsingToolbarLayout
CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.confirm_order_mail_layout);
collapsingToolbarLayout.setTitle("My Title");
May it will helps you. Thank you.
Simply you can change any activity name by using
Activityname.this.setTitle("Title Name");
Try this, you can define title directly in 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:title="some title"
app:popupTheme="#style/AppTheme.PopupOverlay">
To set the title for each Navbar fragment title
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
myView = inflater.inflate(R.layout.second_layout, container, false);
getActivity().setTitle("title");
return myView;
}
Try this .. this method works for me..!! hope it may help somebody..!!
<android.support.v7.widget.Toolbar
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/my_awesome_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" >
<TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:singleLine="true"
android:text="Toolbar Title"
android:textColor="#android:color/white"
android:textSize="18sp"
android:textStyle="bold" />
</android.support.v7.widget.Toolbar>
To display logo in toolbar try the below snippet.
// Set drawable
toolbar.setLogo(ContextCompat.getDrawable(context, R.drawable.logo));
Let me know the result.
getSupportActionBar().setTitle("Your Title");
Please see https://code.google.com/p/android/issues/detail?id=77763. Apparently it is supposed to work like that. Once you call the setSupportActionBar() method call, it then is the responsibility of the ActionBar delegate to route the call to the correct view.
It's not just about .setTitle
more methods of Support Toolbar (Appcompat v7) in onCreate works only with
getSupportActionBar().method()
and don't work with mToolbar.method()
examples:
getSupportActionBar().setTitle("toolbar title");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
though next methods works fine without getSupportActionBar() in onCreate
mToolbar.setVisibility(View.VISIBLE);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//
}
Problem only with onCreate event, you still can use mToolbar.setTitle() later instead of annoying getSupportActionBar().setTitle(), for example if you add this in onCreate it will work (because it will be executed later, after onCreate)
mHandler.post(new Runnable() {
#Override
public void run() {
mToolbar.setTitle("toolbar title");
}
});
I prefer to use this solution https://stackoverflow.com/a/35430590/4548520 than https://stackoverflow.com/a/26506858/4548520 because if you change title many times (in different functions) it's more comfortable to use mToolbar.setTitle() than longer getSupportActionBar().setTitle() one and you don't see annoying notification about null exception like with getSupportActionBar().setTitle()
For anyone who needs to set up the title through the Toolbar some time after setting the SupportActionBar (#sorianiv) AND your Toolbar is inside a CollapsingToolbarLayout, read this:
mToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
Toolbar toolbar = findViewById(R.id.toolbar);
//toolbar.setTitle(""); // no need to do this
//mToolbarLayout.setTitle("Title"); // if you need an initial title, do this instead
setSupportActionBar(toolbar);
Then later,
mToolbarLayout.setTitle("New Title");
I tried to rename the toolbar from the fragment
It helped me, I hope to help someone else
Activity activity = this.getActivity();
Toolbar toolbar = (Toolbar) activity.findViewById(R.id.detail_toolbar);
if (toolbar != null) {
activity.setTitle("Title");
}
//toolbar.setTitle("Title"); did not give the same results
Screenshot:
Application title will not show as default title on every activity, you can insert different title on every activity. On your activity file bellow the onCreate just paste a single line to set title,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Your Title Here");
Just change the text "Your Title Here" to your text.
Simply use this in your adapter,
Where MainActivity is your AppCompactActivity.
Call it from anywhere.
((MainActivity) context).getSupportActionBar().setTitle(titles.get(position));
I made it work by using -
toolbar.post(new Runnable() {
#Override
public void run() {
toolbar.setTitle("My Title");
}
});
If you are using CollapsibleToolbarLayout along with Toolbar then you will need to set title in both the layouts
set your Toolbar as action bar in onCreate method
protected void setUpToolBar() {
if (mToolbar != null) {
((HomeActivity) getActivity()).setSupportActionBar(mToolbar);
mToolbar.setTitleTextColor(Color.WHITE);
mToolbar.setTitle("List Detail");
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity()
.getSupportFragmentManager().popBackStack();
}
});
((HomeActivity) getActivity()).getSupportActionBar()
.setDisplayHomeAsUpEnabled(true);
}
}
Later simply update title of toolbar using setTitle method
mToolbar .setTitle(productFromShoppingList.getProductName());
mCollapsingToolbar.setTitle(productFromShoppingList.getProductName());
I have a strange behaviour that may can help you.
This is working but it has no effect in onCreate only:
toolbar.setTitle("title");
Try to use this in onCreate:
yourActivityName.this.setTitle("title")
This can be done by setting the android:label attribute of your activity in the AndroidManifest.xml file:
<activity android:name="my activity"
android:label="The Title I'd like to display" />
And then add this line to the onCreate():
getSupportActionBar().setDisplayShowTitleEnabled(true);
Try this:
Xml Code
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="120dp"
android:id="#+id/tool_bar"
android:background="#color/tablayout"
android:theme="#style/ToolBarStyle"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:layout_gravity="center"
android:id="#+id/toolbar_title"
android:textSize="18sp"
android:textColor="#color/white"/>
</android.support.v7.widget.Toolbar>
Java Code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
toolbar_text = (TextView)findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.setLogo(R.drawable.ic_toolbar);
}
If your goal is to set a static string in the toolbar, the easiest way to do it is to simply set the activity label in AndroidManifest.xml:
<activity android:name=".xxxxActivity"
android:label="#string/string_id" />
The toolbar will get this string without any code. (works for me with v27 libraries.)
To change the title for each different activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pizza);
setTitle(getResources().getText(R.string.title));
}
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//custom toolbaar
getSupportActionBar().setTitle("Abhijeet");
}
}
Though not immediately relevant to this particular setup, I found that removing "CollapsingToolbarLayout" from my XML that was wrapping my toolbar inside of an AppBarLayout made everything work.
So, this:
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_height="?attr/actionBarSize"
app:layout_scrollFlags="scroll|enterAlways"
app:navigationIcon="#drawable/ic_arrow_back_white_24dp" />
</android.support.design.widget.AppBarLayout>
Instead of this:
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.design.widget.CollapsingToolbarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/collapsingToolbar"
android:minHeight="?attr/actionBarSize"
app:layout_scrollFlags="enterAlways|scroll|snap">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_height="?attr/actionBarSize"
app:navigationIcon="#drawable/ic_arrow_back_white_24dp" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
Then, I set the title in the activity's onCreate, before setSupportActionBar() is called.
Make sure you add this option:
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_TITLE);
The answer is in the documentation (which you can find here):
To use the ActionBar utility methods, call the activity's
getSupportActionBar() method. This method returns a reference to an
appcompat ActionBar object. Once you have that reference, you can call
any of the ActionBar methods to adjust the app bar. For example, to
hide the app bar, call ActionBar.hide().
That is the solution you actually found. Just thought of giving a reference to the official documentation (which apparently few tend to read).
In Kotlin you can do this:
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
class SettingsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_settings)
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setTitle(R.string.title)
}
override fun onSupportNavigateUp() = true.also { onBackPressed() }
}
This is happening because you are using Toolbar and ActionBar both. Now as you want to use Toolbar as an action bar, the first thing you need to do is disable the decor provided action bar.
The easiest way is to have your theme extend from Theme.AppCompat.NoActionBar.