Custom icon in Android toolbar - android

I'm trying to use define a custom icon in the support Toolbar but the only icon shown is a left arrow... I tried to set it in the layout and programmatically but the result is the same.
Here is my Activity
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
toolbar.setNavigationIcon(R.drawable.ic_launcher);
toolbar.setTitle("");
setSupportActionBar(toolbar);
}
And my toolbar layout
<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/my_toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
app:navigationIcon="#drawable/ic_action_bar"
android:minHeight="#dimen/action_bar_size"
android:background="?attr/colorPrimary"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
/>

Just tried it myself and the issue seems to be that you have to call setNavigationIcon after setSupportActionBar(toolbar). Otherwise it'll only show the arrow as you've described.
So to fix this issue just change the code like this:
//...
Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_launcher);
toolbar.setTitle("");
Note: Same goes for setting the title, contentDescription etc. I don't know if this a bug or if it is intended, but it's definitely kinda strange.

In case you want to change menu icon. (maybe somebody will need it)
In your activity
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_info, menu);
return true;
}
in your menu folder in res. (menu_info.xml)
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/menu_info_action"
android:icon="#drawable/ic_info_icon"
android:title="#string/information"
app:showAsAction="ifRoom"/>
</menu>

The current most efficient way to achieve this:
first display the left hand side icon correctly, call this function in onCreateView or onCreate:
protected void enableDisplayHomeAsHome(boolean active) {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(active); // switch on the left hand icon
actionBar.setHomeAsUpIndicator(R.drawable.ic_action_home); // replace with your custom icon
}
}
Now you can intercept this button press in your activity:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: { //index returned when home button pressed
homeButtonPressed();
return true;
}
}
return super.onOptionsItemSelected(item);
}

ActionBar.setHomeAsUpIndicator(...);
This one works for me.

Related

Android ToolBar Menu Item not Clickable

My android app menu item is not clickable I Add app:showAsAction="always" and android:enabled="true" to the menu item and The Item Button is shown but it's not clickable, What Im missing here ?
App Theme : parent="Theme.MaterialComponents.DayNight.DarkActionBar"
Layout :
<?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:theme="#style/ThemeOverlay.AppCompat.ActionBar"
android:orientation="vertical"
tools:context=".Settings.ReportTable">
<androidx.appcompat.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/colorPrimary"
android:id="#+id/toolbar"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/balance_table_SV"/>
</LinearLayout>
Activity :
public class ReportTable extends AppCompatActivity {
ScrollView balance_table_SV;
TableLayout tableLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_report_table);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.inflateMenu(R.menu.excel);
balance_table_SV = findViewById(R.id.balance_table_SV);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.excel, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.menu.excel) {
export_to_excel();
}
return super.onOptionsItemSelected(item);
}
}
First of all, it looks like you're comparing the item ID to the resource ID of the entire menu (R.menu.excel). You should have an ID for each menu item to use for click handling:
<item android:id="#+id/excel" />
if(item.getItemId() == R.id.excel) { ... }
Secondly there seems to be quite a bit of confusion here between the Toolbar and the Android action bar. You are you using a mixture of both in the code you have provided which is causing the inconsistency.
Firstly, if you're using a Toolbar in your layout, you don't need the action bar at all, therefore you should be inheriting from a NoActionBar Material Components theme (such as Theme.MaterialComponents.DayNight.NoActionBar). Then in order to setup your Toolbar you have two options:
Set the Toolbar as the action bar
With this approach you can register the Toolbar to act as the action bar for an activity, which means it correctly triggers the onOptionsItemSelected callback etc. So to do this we need to register it in onCreate:
setSupportActionBar(toolbar);
Then you should probably be using onCreateOptionsMenu to inflate the menu instead of Toolbar.inflateMenu just as you've already done in your code:
getMenuInflater().inflate(R.menu.excel, menu);
And finally to listen for menu item clicks, you can override onOptionsItemSelected and check the item ID as I outlined above.
Setup the Toolbar independently
Instead of registering the Toolbar as the action bar, you can instead just use the Toolbar like any regular view and set it up directly. Firstly to inflate the menu you can call:
toolbar.inflateMenu(R.menu.excel);
Then in order to listen for click events you can attach an OnMenuItemClickListener as follows:
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
...
}
});
Both approaches are valid but I personally prefer the second. It seems strange to try and work around the activity lifecycle when you could just treat the Toolbar normally.

Back arrow in tool bar in order to go to previous activity [duplicate]

I'm migrating from ActionBar to Toolbar in my application.
But I don't know how to display and set click event on Back Arrow on Toolbar like I did on Actionbar.
With ActionBar, I call mActionbar.setDisplayHomeAsUpEnabled(true).
But there is no the similar method like this.
Has anyone ever faced this situation and somehow found a way to solve it?
If you are using an ActionBarActivity then you can tell Android to use the Toolbar as the ActionBar like so:
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(toolbar);
And then calls to
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
will work. You can also use that in Fragments that are attached to ActionBarActivities you can use it like this:
((ActionBarActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((ActionBarActivity) getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);
If you are not using ActionBarActivities or if you want to get the back arrow on a Toolbar that's not set as your SupportActionBar then you can use the following:
mActionBar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_action_back));
mActionBar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//What to do on back clicked
}
});
If you are using android.support.v7.widget.Toolbar, then you should add the following code to your AppCompatActivity:
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
I see a lot of answers but here is mine which is not mentioned before. It works from API 8+.
public class DetailActivity extends AppCompatActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
// toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// add back arrow to toolbar
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
finish(); // close this activity and return to preview activity (if there is any)
}
return super.onOptionsItemSelected(item);
}
There are many ways to achieve that, here is my favorite:
Layout:
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:navigationIcon="?attr/homeAsUpIndicator" />
Activity:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// back button pressed
}
});
you can use the tool bar setNavigationIcon method.
Android Doc
mToolBar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handleOnBackPress();
}
});
If you don't want to create a custom Toolbar, you can do like this
public class GalleryActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
...
getSupportActionBar().setTitle("Select Image");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
}
In you AndroidManifest.xml
<activity
android:name=".GalleryActivity"
android:theme="#style/Theme.AppCompat.Light">
</activity>
you can also put this android:theme="#style/Theme.AppCompat.Light" to <aplication> tag, for apply to all activities
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.back_arrow); // your drawable
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed(); // Implemented by activity
}
});
And for API 21+ android:navigationIcon
<android.support.v7.widget.Toolbar
android:navigationIcon="#drawable/back_arrow"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"/>
I used this method from the Google Developer Documentation:
#Override
public void onCreate(Bundle savedInstanceState) {
...
getActionBar().setDisplayHomeAsUpEnabled(true);
}
If you get a null pointer exception it could depend on the theme. Try using a different theme in the manifest or use this alternatively:
#Override
public void onCreate(Bundle savedInstanceState) {
...
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Then in the manifest, where I set the parent activity for current activity:
<activity
android:name="com.example.myapp.MyCurrentActivity"
android:label="#string/title_activity_display_message"
android:parentActivityName="com.example.myfirstapp.MainActivity" >
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myapp.MyMainActivity" />
</activity>
I hope this will help you!
If you were using AppCompatActivity and have gone down the path of not using it, because you wanted to not get the automatic ActionBar that it provides, because you want to separate out the Toolbar, because of your Material Design needs and CoordinatorLayout or AppBarLayout, then, consider this:
You can still use the AppCompatActivity, you don't need to stop using it just so that you can use a <android.support.v7.widget.Toolbar> in your xml. Just turn off the action bar style as follows:
First, derive a style from one of the NoActionBar themes that you like in your styles.xml, I used Theme.AppCompat.Light.NoActionBar like so:
<style name="SuperCoolAppBarActivity" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">#color/primary</item>
<!-- colorPrimaryDark is used for the status bar -->
<item name="colorPrimaryDark">#color/primary_dark</item>
...
...
</style>
In your App's manifest, choose the child style theme you just defined, like so:
<activity
android:name=".activity.YourSuperCoolActivity"
android:label="#string/super_cool"
android:theme="#style/SuperCoolAppBarActivity">
</activity>
In your Activity Xml, if the toolbar is defined like so:
...
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
/>
...
Then, and this is the important part, you set the support Action bar to the AppCompatActivity that you're extending, so that the toolbar in your xml, becomes the action bar. I feel that this is a better way, because you can simply do the many things that ActionBar allows, like menus, automatic activity title, item selection handling, etc. without resorting to adding custom click handlers, etc.
In your Activity's onCreate override, do the following:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_super_cool);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Your toolbar is now an action bar and you can use it like you always do, for example:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
If your are using the androidx.appcompat.app.AppCompatActivity just use:
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Then just define in the Manifest.xml the parent Activity.
<activity
android:name=".MyActivity"
...>
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".ParentActivity" />
</activity>
Instead if you are using a Toolbar and you want a custom behavior just use:
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
app:navigationIcon="?attr/homeAsUpIndicator"
.../>
and in your Activity:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//....
}
});
In Kotlin it would be
private fun setupToolbar(){
toolbar.title = getString(R.string.YOUR_TITLE)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
}
// don't forget click listener for back button
override fun onSupportNavigateUp(): Boolean {
onBackPressed()
return true
}
Simple and easy way to show back button on toolbar
Paste this code in onCreate method
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
Paste this override method outside the onCreate method
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()== android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
MyActivity extends AppCompatActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(arrow -> onBackPressed());
}
Easily you can do it.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
Credits:
https://freakycoder.com/android-notes-24-how-to-add-back-button-at-toolbar-941e6577418e
First, you need to initialize the toolbar :
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
then call the back button from the action bar :
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
In the AppCompatActivity for example you can do
public class GrandStatActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grand_stat);
}
#Override
public void onResume() {
super.onResume();
// Display custom title
ActionBar actionBar = this.getSupportActionBar();
actionBar.setTitle(R.string.fragment_title_grandstats);
// Display the back arrow
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
// Back arrow click event to go to the parent Activity
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
In your manifest file for the activity where you want to
add a back button, we will use the property android:parentActivityName
<activity
android:name=".WebActivity"
android:screenOrientation="portrait"
android:parentActivityName=".MainActivity"
/>
P.S. This attribute was introduced in API Level 16.
If you want to get the back arrow on a Toolbar that's not set as your SupportActionBar:
(kotlin)
val resId = getResIdFromAttribute(toolbar.context, android.R.attr.homeAsUpIndicator)
toolbarFilter.navigationIcon = ContextCompat.getDrawable(toolbar.context, resId)
toolbarFilter.setNavigationOnClickListener { fragmentManager?.popBackStack() }
to get res from attributes:
#AnyRes
fun getResIdFromAttribute(context: Context, #AttrRes attr: Int): Int {
if (attr == 0) return 0
val typedValueAttr = TypedValue()
context.theme.resolveAttribute(attr, typedValueAttr, true)
return typedValueAttr.resourceId
}
This worked perfectly
public class BackButton extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_box);
Toolbar chatbox_toolbar=(Toolbar)findViewById(R.id.chat_box_toolbar);
chatbox_toolbar.setTitle("Demo Back Button");
chatbox_toolbar.setTitleTextColor(getResources().getColor(R.color.white));
setSupportActionBar(chatbox_toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
chatbox_toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Define Back Button Function
}
});
}
}
Follow 3 steps if you want to handle your problem fastly & simply:
Add file ic_arrow.xml to Drawable folder with some codes below (add codes below into ic_arrow.xml)
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:width="24dp"
android:height="24dp"
android:tint="#color/black"
android:viewportWidth="24"
android:viewportHeight="24"
tools:ignore="ExtraText">
<path
android:fillColor="#android:color/white"
android:pathData="M20,11H7.83l5.59,-5.59L12,4l-8,8 8,8 1.41,-1.41L7.83,13H20v-2z" />
</vector>
Add ImageButton to Toolbar (make sure the Toolbar customized, not Titlebar or Statusbar) - You can customize the ImageButton (arrow button) position if you want
<ImageButton
android:id="#+id/arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_arrow"
android:layout_marginTop="15dp"
android:layout_marginStart="15dp"
android:background="#android:color/transparent"
tools:ignore="ContentDescription" />
Add the setArrowButton method to DetailActivity.java (or any xxxActivity.java that you need)
public class DetailActivity extends AppCompatActivity {
ImageButton arrowButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
arrowButton = findViewById(R.id.arrow);
setArrowButton(arrowButton);
}
public void setArrowButton(ImageButton arrowButton) {
arrowButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish(); //will close the moment activity and return to
//the last activity
}
});
}
}
Done
Preview about arrowButton
Add this to activity's xml in layout folder:
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/prod_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
Make toolbar clickable, add these to onCreate method:
Toolbar toolbar = (Toolbar) findViewById(R.id.prod_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
With Kotlin it became:
Xml:
<include
android:id="#+id/tbSignToolbar "
layout="#layout/toolbar_sign_up_in"/>
In your Activity:-
setSupportActionBar(tbSignToolbar as Toolbar?)//tbSignToolbar :id of your toolbar
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
Possibly a more reliable way to get the up icon from your theme (if not using the toolbar as your action bar):
toolbar.navigationIcon = context.getDrawableFromAttribute(R.attr.homeAsUpIndicator)
In order to turn the theme attribute into a drawable I used an extension function:
fun Context.getDrawableFromAttribute(attributeId: Int): Drawable {
val typedValue = TypedValue().also { theme.resolveAttribute(attributeId, it, true) }
return resources.getDrawable(typedValue.resourceId, theme)
}
If you are using DrawerLayout with ActionBarDrawerToggle, then to show Back button instead of Menu button (and viceversa), you need to add this code in your Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.application_name, R.string.application_name);
mDrawerLayout.addDrawerListener(mDrawerToggle);
mDrawerToggle.setHomeAsUpIndicator(R.drawable.ic_arrow_back_white_32dp);
mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onBackPressed(); // Or you can perform some other action here when Back button is clicked.
}
});
mDrawerToggle.syncState();
// ...
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item))
return true;
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
// ...
}
return super.onOptionsItemSelected(item);
}
public void showBackInToolbar(boolean isBack) {
// Remove next line if you still want to be able to swipe to show drawer menu.
mDrawerLayout.setDrawerLockMode(isBack ? DrawerLayout.LOCK_MODE_LOCKED_CLOSED : DrawerLayout.LOCK_MODE_UNLOCKED);
mDrawerToggle.setDrawerIndicatorEnabled(!isBack);
mDrawerToggle.syncState();
}
So when you need to show Back button instead of Menu button, call showBackInToolbar(true), and if you need Menu button, call showBackInToolbar(false).
You can generate back arrow (ic_arrow_back_white_32dp) over here, search arrow_back in Clipart section (use default 32dp with 8dp padding). Just select the color you want.
You can always add a Relative layout or a Linear Layout in your Toolbar and place a Image view for back icon or close icon anywhere in toolbar as you like
For example I have used Relative layout in my toolbar
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar_top"
android:layout_width="match_parent"
android:layout_height="35dp"
android:minHeight="?attr/actionBarSize"
android:nextFocusDown="#id/netflixVideoGridView"
app:layout_collapseMode="pin">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Myflix"
android:textAllCaps="true"
android:textSize="19sp"
android:textColor="#color/red"
android:textStyle="bold" />
<ImageView
android:id="#+id/closeMyFlix"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
app:srcCompat="#drawable/vector_close" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
And it looks like this:
You can add click listener on that image view from Activity or fragment like this.
closeMyFlix.setOnClickListener({
Navigator.instance.showFireTV( activity!!.supportFragmentManager)
})
If you are using JetPack Navigation.
Here is the layout for MainActivity
<androidx.constraintlayout.widget.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"
tools:context=".MainActivity">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolBar"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</androidx.appcompat.widget.Toolbar>
<fragment
android:id="#+id/my_nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
app:defaultNavHost="true"
app:layout_constraintTop_toBottomOf="#id/toolBar"
app:layout_constraintBottom_toTopOf="parent"
app:navGraph="#navigation/nav_graph"/>
SetUp your toolbar in your activity like below in onCreate() of your Activity class.
val navHostFragment = supportFragmentManager
.findFragmentById(R.id.my_nav_host_fragment) as NavHostFragment? ?: return
val navController = navHostFragment.findNavController()
val toolBar = findViewById<Toolbar>(R.id.toolBar)
setSupportActionBar(toolBar) // To set toolBar as ActionBar
setupActionBarWithNavController(navController)
setupActionBarWithNavController(navController) Will create a back button on the toolBar if needed and handles the backButton functionality.
If you need to write a CustomBack functionality, create a callBack as below on your fragment onCreate() method
val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
// Handle the back button event
}
From Documentation:https://developer.android.com/guide/navigation/navigation-custom-back
maybe it will help someone,I didn't find in the answares the thing I did by the end:
with ActionBarDrawerToggle mDrawerToggle;
to show the back arrow in toolbar set:
mDrawerToggle.setDrawerIndicatorEnabled(false);
and if you want it to show the hamburger in the toolbar:
mDrawerToggle.setDrawerIndicatorEnabled(true);

How to get actionbar back button width programmatically?

I am setting toolbar to my actionbar, but I have activities when I disable home button and the title in toolbar is not centralized so I would like to get actionbar back button with programmatically to set toolbar.setContentInsetsAbsolute(0, 0);
You need to do something like this for the TextView inside the Toolbar which contains your title:
android:paddingLeft="?attr/actionBarSize"
try this
toolbar = (Toolbar) findViewById(R.id.toolbar_editprofile);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.back_arrow));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can set by setting Style, set activity theme in the manifest as no action bar and use toolbar manually in layout and set the style as you want and you can also change the size of text or you can inflate image in toolbar by using style.
<style name="Theme.MyFancyTheme" parent="android:Theme.Holo">
<item name="android:homeAsUpIndicator">#drawable/ic_toolbar_back_button</item>
</style>
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:layout_gravity="top"
android:background="#android:color/transparent"
android:visibility="visible"
app:theme="#style/Theme.MyFancyTheme">

Android How can make toolbar title and subtitle have touch effect?

This image capture form whatsapp, how can i do that?
I want to do
It's my app
and my code
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setTitle("Subject");
mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
});
mToolbar.setNavigationIcon(R.drawable.back);
mToolbar.setLogo(R.drawable.common_plus_signin_btn_icon_light);
setSupportActionBar(mToolbar);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Log.i("ChatActivity", "Back");
onBackPressed();
}
});
In my app, only navigation icon part have touch effect, then i touch on title part, it no touch effect.
Try this:
1. Create a new layout called 'my_toolbar' for instance.
<?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:elevation="4dp"
app:contentInsetStart="0dp"
app:theme="#style/ActionBarTheme">
<TextView
android:id="#+id/toolbar_custom_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content""/>
</android.support.v7.widget.Toolbar>
include this layout in your activity layout.
in onCreate(...), find your toolbar view, and in it find your TextView and apply an onClickListener on it
mToolBar = (Toolbar) findViewById(R.id.toolbar);
if (mToolBar != null) {
setSupportActionBar(mToolBar);
}
super.setTitle("");
mTitleTextView = (TextView) findViewById(R.id.toolbar_custom_title);
mTitleTextView.setOnClickListener(...);
You can edit actionbar.
getActionBar().setIcon(R.drawable.my_icon);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
if it doesnt work, you can try this. So you can put image in titlebar.
getSupportActionBar().setIcon(R.drawable.my_icon);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if you want to get image click, u can get from optionsitemselected like that
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case android.R.id.home:
//do something
return true;
}
return super.onOptionsItemSelected(item);
}

onCreateOptionsMenu is never called

I am having some trouble getting an options menu working in Android. I have built apps before, and they all worked fine, but now the menu just doesn't pop up.
The code:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.activity_video, menu);
return true;
}
the whole method is never even called (checked by setting a breakpoint). The activity is super-simple, it just has a VideoView in it, with an OnTouchListener set.
I am using Android 4.0.4 on a Samsung Galaxy 10.1, API level 15, minSDK 15. Am I missing something?
In the latest versions of Android when using the compat library for toolbar, is very common that this happens, in order to get the menu items to display in the toolbar you must do the following:
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
Call setHasOptionsMenu function from onCreate first. The onCreateOptionsMenu will be automatically called.
Try this:
setHasOptionsMenu(true)
If the phone you test on has a menu button onCreateOptionsMenu wont't be called on start with the theme:
android:theme="#android:style/Theme.Black.NoTitleBar"
But when you click the menu button the onCreateOptionsMenu will be called. I don't know what happens on phones without hardware buttons...
In the method: Fragment#onCreateView(...) you should put:
setHasOptionsMenu(true);
Then your method will be called.
That is because the activity does not have the toolbar.
There are 2 steps in order to do it.
First, you need to add the toolbar in your activity.xml which is in res/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"">
<!-- add this part-->
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Second, let your activity append it
in JAVA
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
or in Kotlin
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
I was having the same problem (menu not showing up, onCreateOptionsMenu not being called).
If you are calling this within a fragment, you need to override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) not public boolean onCreateOptionsMenu(Menu menu). Fragments do not use the latter, so they will never even call it.
Activity menu
Fragment menu
This happens because you have defined a Theme in your styles.xml that has something like:
<style name="AppTheme" parent="Theme.AppCompat.Light.**NoActionBar**">
You can manually create a toolbar, and then yo have to add it to your Activity.
The xml for the toolbar view could be something like:
<?xml version="1.0" encoding="utf-8"?>
<androidx.appcompat.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light">
</androidx.appcompat.widget.Toolbar>
Then, in the Activity, you have to "display" it :
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayShowTitleEnabled(false);
}
And now, you can create the menu with the known onCreateOptionsMenu
I had the same issue. My problem was solved by inheritance of a different activity class.
So I had been doing:
public class WelcomeActivity extends Activity
but changed this to:
public class WelcomeActivity extends AppCompatActivity
This way I was saying that say an action bar can be added to your activity.
Maybe you also have overrode onKeyDown method and made it always return true. Returning true means that keyEvent will be prevented from being propagated further. See code below:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
/*
handling event
*/
return true; //onCreateOptionsMenu won't be invoked.
}
I had a similar issue, but a different solution I am sharing with the community (as it took me one hour to understand what was happening):
abstract class BaseActivity : AppCompatActivity{
override fun onCreate(savedInstanceState: Bundle?) {
setSupportActionBar(my_toolbar)
}
}
class MyActivity : BaseActivity{
// TODO : some good stuff
}
where my_toolbar is an object created in my xml file through dataBinding.
The issue looks the same, no toolbar appear, no call to onCreateOptionsMenu.
My solution was to promote this code to the child class and not to that basic, as my_toolbar is only initialized as the child class is built.
If above answer doesn't work, make sure that you are using the same id of toolbar.
layout_app_bar.xml
<androidx.appcompat.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">
activiy_main.xml
<include
android:id="#+id/app_bar"
layout="#layout/layout_app_bar" />
in java file:
don't call:
Toolbar tb = findViewById(R.id.toolbar);
please call:
Toolbar tb = findViewById(R.id.app_bar);
Try This It works for me:---
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.home_page_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_delete:
Toast.makeText(this, "You pressed the Delete!",
Toast.LENGTH_LONG).show();
break;
case R.id.menu_setting:
Intent intent=new Intent(HomePage.this,Setting.class);
startActivity(intent);
finish();
Toast.makeText(this, "You pressed the Setting!",
Toast.LENGTH_LONG).show(); break;
}
return super.onOptionsItemSelected(item);
}

Categories

Resources