Toolbar does not show up in Xamarin.Android - android

I'm trying to replace an ActionBar with a toolbar, but the toolbar doesn't show up. I don't understand why my page is still blank without the toolbar, what am I missing?
My style:
<style name="MyThemeActionBar" parent="Theme.AppCompat.Light">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
My toolbar.axml:
<?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_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:layout_width="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/toolbartitile"
android:text="Kodej"/>
</android.support.v7.widget.Toolbar>
My activity:
[Activity(Label = "MainLoginActivity" , Theme = "#style/MyThemeActionBar")]
public class MainLoginActivity : AppCompatActivity
{
private ISharedPreferences sp;
private Android.Support.V7.Widget.Toolbar toolbar;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.MainLogin);
toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
sp = GetSharedPreferences(null, FileCreationMode.Private);
TextView tv = FindViewById<TextView>(Resource.Id.emailMain);
tv.Text = sp.GetString("email", null);
tv.Click += (object sender, EventArgs e) =>
{
Android.Support.V7.App.AlertDialog.Builder ad = new Android.Support.V7.App.AlertDialog.Builder(this);
ad.SetTitle("Logout");
ad.SetMessage("Are you sure you want to logout");
ad.SetPositiveButton("Yes", (senderAlert, args) =>
{
ISharedPreferencesEditor editor = sp.Edit();
editor.Remove("email");
editor.Apply();
StartActivity(typeof(MainActivity));
Finish();
});
ad.SetNegativeButton("Cancel", (senderAlert, args) => {});
Dialog dialog = ad.Create();
dialog.Show();
};
}
}

I think the problem could be with the code:
toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
Since you didn't post your code of your MainLogin layout, when you code this in your MainLoginActivity, the context is MainLoginActivity, and you should make sure there is a Android.Support.V7.Widget.Toolbar which ID is toolbar existing in the MainLogin layout, otherwise, this will return a null, and it won't throw an exception when you SetSupportActionBar(toolbar);.
To solve this issue, you can:
Move your layout for your Toolbar into MainLogin layout.
Or keep your Toolbar in your toolbar layout but use it in your MainLogin layout for example like this:
MainLogin layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include android:id="#+id/toolbar"
layout="#layout/mytoolbar" />
</LinearLayout>

Related

Change font of tabs, fontFamily not working

I have an issue defining a custom font for tabs in my Xamarin.Forms app (on android).
The Tabbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.TabLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/sliding_tabs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:tabTextAppearance="#style/TabbarTitleText"
app:tabTextColor="#android:color/white"
app:tabSelectedTextColor="#android:color/white"
app:tabIndicatorColor="#android:color/white"
app:tabGravity="fill"
app:tabMode="fixed" >
<!--<TextView
style="#style/TextAppearance.AppCompat.Widget.ActionBar.Title"
android:textColor="#android:color/white"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:id="#+id/tabbar_title" />-->
</android.support.design.widget.TabLayout>
I tried to put a textview but doesn't compile.
The style i created in styles.xml is applied except for the fontFamily property
<style name="TabbarTitleText" parent="TextAppearance.AppCompat">
<item name="android:textSize">15dp</item>
<item name="android:fontFamily">fonts/Futura Book.ttf</item>
<item name="android:textAllCaps">false</item>
</style>
Are all parameters correct? Especially parent=
If i use a custom renderer, it doesn't work because there is no child element to detect in TabLayout.
For my Toolbar it works because the TextView receive the custom render parameters.
<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="wrap_content"
android:textColor="#android:color/white"
android:theme="#style/MyActionBar"
android:background="#drawable/custom_background_bar"
android:elevation="3dp">
<TextView
style="#style/TextAppearance.AppCompat.Widget.ActionBar.Title"
android:textColor="#android:color/white"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:id="#+id/toolbar_title" />
.
public class MyToolBarRenderer : NavigationPageRenderer
{
public MyToolBarRenderer(Context context) : base(context)
{
}
private Support.Toolbar _toolbar;
public override void OnViewAdded(Android.Views.View child)
{
base.OnViewAdded(child);
if (child.GetType() == typeof(Support.Toolbar))
_toolbar = (Support.Toolbar)child;
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
var page = this.Element as NavigationPage;
if (page != null && _toolbar != null)
{
Typeface tf = Typeface.CreateFromAsset(Android.App.Application.Context.Assets, "fonts/Futura Book.ttf");
TextView title = (TextView)_toolbar.FindViewById(Resource.Id.toolbar_title);
title.SetText(page.CurrentPage.Title, TextView.BufferType.Normal);
title.SetTypeface(tf, TypefaceStyle.Normal);
}
}
}
All my views are NavigationPages, not any TabbedPage.
In App.xaml.cs i have this
MainPage = new NavigationPage(new MainPage())
Then in MainPage
switch (Device.RuntimePlatform)
{
case Device.iOS:
centerPage = new NavigationPage(new Center_Main())
{
Title = TitleCenter
};
......
break;
default:
centerPage = new Center_Main()
{
Title = TitleCenter
};
rightPage = new Right_Main()
{
Title = TitleRight
};
.......
break;
}
Then every xaml is a ContentPage. I basically created a Master Detail project at beginning.

How to dynamically change ToolbarResource

I'm developing PCL aplication in Xamarin.Forms.
I want to have a customized toolbar for my main page (with custom layout, logo etc.) and standard toolbars for all other pages (with back button and some ContentPage.ToolbarItems).
I created custom file MainToolbar.axml in layouts folder and wrote
ToolbarResource = Resource.Layout.MainToolbar;
in OnCreate event handler in MainActivity.cs.
Now I can see my custom toolbar not only on main page but on all pages. I try to write ToolbarResource = Resource.Layout.Toolbar; in OnDisappearing event handler of the main page, but it doesn't affect. So how can I change the toolbar back to standard? I don't have android renderers for all pages and I think there is must be a better way. Thanks.
The basic answer you cannot change the whole toolbar but you can develop 2 layouts: main and not main and programatically set their visibility in a single toolbar widget or add/remove them from the toolbar. I would do it this way. In PCL in your main page
protected override void OnDisappearing()
{
base.OnDisappearing();
MessagingCenter.Send<Page, string>(this, "toolbar", "notmain");
}
protected override void OnAppearing()
{
base.OnAppearing();
MessagingCenter.Send<Page, string>(this, "toolbar", "main");
}
In your MainActivity after you initialize Forms
protected override void OnCreate(Bundle bundle)
{
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
var mainToolbarLayout = FindViewById<LinearLayout>(Resource.Id.toolbarMainLayout);
MessagingCenter.Subscribe<Page, string>(this, "toolbar", (page, toolbar) =>
{
if (toolbar == "main")
{
mainToolbarLayout.Visibility = ViewStates.Visible;
}
else
{
mainToolbarLayout.Visibility = ViewStates.Gone;
}
});
}
Here is a sample of Toolbar
<?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="wrap_content"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:contentInsetEnd="0dp"
app:contentInsetLeft="0dp"
app:contentInsetRight="0dp"
app:contentInsetStart="0dp"
android:clipToPadding="false"
>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/toolbarMainLayout"
android:background="#android:color/holo_green_light" />
</android.support.v7.widget.Toolbar>

Visible ActionBar with opened NavDrawer

Is it possible to keep the actionbar visible using the mikepenz's material drawer library?
Yes this is possible. Just see the sample application. This contains the CustomContainerActivity which showcases how you can have a Drawer which is below the Toolbar
public class CustomContainerActivity extends AppCompatActivity {
//save our header or result
private Drawer result = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample_custom_container_dark_toolbar);
// Handle Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(R.string.drawer_item_custom_container_drawer);
//Create the drawer
result = new DrawerBuilder(this)
//this layout have to contain child layouts
.withRootView(R.id.drawer_container)
.withToolbar(toolbar)
.withActionBarDrawerToggleAnimated(true)
.addDrawerItems(
new PrimaryDrawerItem().withName(R.string.drawer_item_home).withIcon(FontAwesome.Icon.faw_home),
new PrimaryDrawerItem().withName(R.string.drawer_item_free_play).withIcon(FontAwesome.Icon.faw_gamepad),
new PrimaryDrawerItem().withName(R.string.drawer_item_custom).withIcon(FontAwesome.Icon.faw_eye),
new SectionDrawerItem().withName(R.string.drawer_item_section_header),
new SecondaryDrawerItem().withName(R.string.drawer_item_settings).withIcon(FontAwesome.Icon.faw_cog),
new SecondaryDrawerItem().withName(R.string.drawer_item_help).withIcon(FontAwesome.Icon.faw_question).withEnabled(false),
new SecondaryDrawerItem().withName(R.string.drawer_item_open_source).withIcon(FontAwesome.Icon.faw_github),
new SecondaryDrawerItem().withName(R.string.drawer_item_contact).withIcon(FontAwesome.Icon.faw_bullhorn)
)
.withSavedInstance(savedInstanceState)
.build();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
//add the values which need to be saved from the drawer to the bundle
outState = result.saveInstanceState(outState);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
//handle the back press :D close the drawer first and if the drawer is closed close the activity
if (result != null && result.isDrawerOpen()) {
result.closeDrawer();
} else {
super.onBackPressed();
}
}
}
Also note the different xml layout which is used in this Activity.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:gravity="center"
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:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
android:elevation="4dp" />
<!-- the layout which will contain (host) the drawerLayout -->
<FrameLayout
android:layout_below="#id/toolbar"
android:id="#+id/drawer_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- the layout which will be the content of the activity (which will be hosted inside the drawer (NOT the list of the drawer)) -->
<FrameLayout
android:id="#+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtLabel"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test"
android:textSize="16sp" />
</FrameLayout>
</FrameLayout>
</RelativeLayout>
This will produce the following:

Android ActionBar -- How to add logo in centrelly aligned

I am new in android development and I want make a navigation drawer for my client.
How can I add a logo to my action bar in navigation drawer and remove the title.
my code :
Activity
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#D5D2D4")));
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
actionBar.setDisplayUseLogoEnabled(true);
}
Manifest Activity
<activity
android:name=".activity.Grid_Home_Activity"
android:label="#string/title_activity_grid__home_"
android:theme="#style/Theme.ActionBarJp">
</activity>
Styles
<style name="Theme.ActionBarJp" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="actionBarSize">60dp</item>
<item name="logo">#drawable/logo</item>
<item name="displayOptions">useLogo|showHome</item>
</style>
Can anyone help ?
you can use https://github.com/jgilfelt/SystemBarTint this Library
and use as below.
public ActionBar enableCustomCenterTitle(Context context, boolean isShowBack, boolean isWhite) {
ActionBar actionBar = enableCustomTitle();
View actionbarLayout = LayoutInflater.from(context).inflate(
R.layout.actionbar_layout, (ViewGroup) actionBar.getCustomView(),false);
if (isWhite) {
actionbarLayout = LayoutInflater.from(context).inflate(
R.layout.actionbar_layout_white, (ViewGroup) actionBar.getCustomView(),false);
TextView back = (TextView) actionbarLayout.findViewById(R.id.action_bar_back);
back.setTextColor(getResources().getColor(R.color.orange));
mTintManager.setStatusBarTintColor(getResources().getColor(R.color.white));
setStatusBarDarkMode(true, this);
}
ActionBar.LayoutParams params = new
ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT,
ActionBar.LayoutParams.MATCH_PARENT, Gravity.CENTER);
View backView = ButterKnife.findById(actionbarLayout, R.id.action_bar_back);
if (isShowBack) {
backView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed();
}
});
backView.setVisibility(View.VISIBLE);
} else {
backView.setVisibility(View.GONE);
}
actionBar.setCustomView(actionbarLayout, params);
return actionBar;
}
ActionBar is deprecated. Use ToolBar .
Then at your Toolbar object center the ImageView with the logo.
Take a look at this
You can use setLogo to set a resDrawable or Drawable object. As to the logo size on the ActionBar, I believe it's 32x32 dp; Optical square, 24x24 dp according to this
To remove the title, just use actionBar.setTitle(""). This code makes it looks like there is no title.
One more thing, You should really change ActionBar to ToolBar.
As actionbar is deprecated, it is better to user ToolBar and can utilize material design concepts in your app.
Do according below:
1. create toolbar.xml in your res folder.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/grey"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/iv_Logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
Open the layout file of your main activity (activity_main.xml) and add the toolbar.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:orientation="vertical">
<include
android:id="#+id/toolbar"
layout="#layout/toolbar" />
</LinearLayout>
In your MainActivity.java, add reference of Toolbar widget in onCreate() method :
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);

In android app Toolbar.setTitle method has no effect – application name is shown as title

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.

Categories

Resources