pressed the back button on the toolbar [duplicate] - android

This question already has answers here:
When toolbar back button is pressed
(4 answers)
Closed 6 years ago.
how can I create a code for my android app where When I pressed the back button on the toolbar (Action Bar) some code will happening.
I tried but it does not work.
Added in main activity. onbackpress method
#Override
public void onBackPressed() {
super.onBackPressed();
stopActivityTask();
}

You can Try this way..
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// this takes the user 'back', as if they pressed the left-facing
triangle icon on the main android toolbar.
// if this doesn't work as desired, another possibility is to call
stopActivityTask(); // finish() here.
getActivity().onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
If Not Work
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// Title and subtitle
toolbar.setTitle(R.string.about_toolbar_title);
toolbar.setNavigationIcon(R.drawable.ic_action_back);
toolbar.setNavigationOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
stopActivityTask();
finish();
}
});

private Toolbar toolbar;
Then add this in your onCreate method
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Then you add these lines :
#Override
public boolean onOptionsItemSelected(MenuItem item) {
/*
ADD WHAT YOU WANT TO DO WHEN ARROW IS PRESSED
*/
return super.onOptionsItemSelected(item);
}

#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// click on icon to go back
//triangle icon on the main android toolbar.
if (id == android.R.id.home) {
//your code
return true;
}
return super.onOptionsItemSelected(item);
}

Related

How to add click on the action bar back button

I am trying to add click functionality on the Actionbar back button. I have tried the below things till now, but unable to get the desired result.
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Observed that the onClick method is not being called when i click on the back button in the action bar
toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
};
drawer.setDrawerListener(toggle);
drawer.post(new Runnable() {
#Override
public void run() {
toggle.syncState();
}
});
toggle.setDrawerIndicatorEnabled(true);
toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onKeyDown(4, null);
}
});
Use the updated code
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
switch (item.getItemId()) {
case android.R.id.home:
showToast("Test");
return true;
}
you can try like this
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
use following code inside your Activity :
//for going back or finish current activity.
#Override
public boolean onSupportNavigateUp() {
finish();
startActivity(new Intent(ResultActivity.this, MainActivity.class));
return true;
}
Below code are for actionBar menu.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.logout) {
// toast Here
return true;
}
if (id == R.id.home) {
// toast Here
return true;
}
return super.onOptionsItemSelected(item);
}
onCreateOptionsMenu() is used for creating your menu & setting your menu.xml
onOptionsItemSelected() is used for selection of menu items & actions.

RecyclerView empty when click icon back in toolbar

I need set back icon in my toolbar. I created my toolbar using android.support.v7.widget.Toolbar and for back using this code first set onClick to my back icon by this code:
ImageView backIcon = findViewById(R.id.back_icon);
backIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(CreateNewItem.this,MainActivity.class);
startActivity(intent);
finish();
}
});
and add this code:
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
it's work and back to activity but my problem it's when using back icon and back to activity see recyclerView is empty and activity not have data. what is my problem?
If You are using Toolbar then no need to set custom back icon, you have to just override this method
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
onBackPressed();
}
return (super.onOptionsItemSelected(menuItem));
}
and enable Toolbar:
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Happy coding!!

How to go back to previous activite(s)?

so i have Activity A,B, and C. Activity A & B both go to activity C. When i am on activity C and I press the back home button on mySupportActionBar, I want to return to the state of activity (from the state i left it in) I came from. How would i accomplish this?
Here is my onOptionsItemSelected(). So currently, it goes back to the designated parent activity i assigned in manifest to avoid my app from crashing. Because the parent activites require strings from intents.
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if(id == android.R.id.home)
{
NavUtils.navigateUpFromSameTask(this);
}
return super.onOptionsItemSelected(item);
}
I would also love to accomplish this onBackPressed().
The back arrow button is the "home" button when you're in a inner activity so you could finish the inner activity or maybe just call the back button
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Use android.R.id.home
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
You also can use setNavigationOnClickListener on toolbar to trigger back button.
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_filter_category);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowTitleEnabled(false);
//back button action
toolbar.setNavigationOnClickListener(view -> finish());
}
}

Toolbar back button does not close current Fragment

I have an activity that loads a Fragment onCreate. And I have a toolbar on that activity that has a button that when clicked will add a new Fragment on top of the one that got created first.
Now on that toolbar, when clicked, I want to remove the newer fragment so that it just displaces the fragment that is in the bottom (older one). I've searched and I kinda have figured it out except for one thing.
I did this so that it tries to see if the toolbar button is pressed:
#Override
public boolean onKeyUp(int keyCode, KeyEvent objEvent) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
return true;
}
return super.onKeyUp(keyCode, objEvent);
}
#Override
public void onBackPressed() {
FragmentManager mFM = getSupportFragmentManager();
if(mFM.findFragmentByTag("NewFragment") != null){
mFM.beginTransaction().remove(mFM.findFragmentByTag("NewFragment")).commit();
}
}
The problem is, "keyCode" is only equals to KEYCODE_BACK when you click the "hardware's back button" and not the back button of the toolbar. What it gives me is keycode 58 and not 4 (KEYCODE_BACK).
I believe what your looking for is the NavigationListener for the Toolbar Widget:
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
but if your using a Theme with an ActionBar and setting a supportActionBar then do something :
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case android.R.id.home:
onBackPressed();
break;
}
return true;
}
It's not clear from your question whether you're asking a Fragment management question (FragmentTransaction remove vs. replace), or a Toolbar button question. I assume the latter...
An Android Toolbar or ActionBar should have actions handled using:
#Override
public Boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case MY_BACK_BUTTON:
myBackPressedHandler();
return (true);
}
return (false);
}
this assumes that your Back button is added as a MenuItem and was given an ID of MY_BACK_BUTTON.
For a Toolbar, you can use a MenuItemClickListener to handle the click events:
mToolbar.setOnMenuItemClickListener(MenuItem menuItem)
{
#Override
public Boolean onMenuItemClick(MenuItem menuItem)
{
// call onOptionsItemSelected, or handle the click here directly
return (thisFragment.onOptionsItemSelected(menuItem));
}
});
If you're referring to the "Up" button on the Toolbar/ActionBar, i.e. setDisplayHomeAsUpEnabled(true), this will have a getItemId() of android.R.id.home and can be handled in a similar fashion:
case android.R.id.home:
myBackPressedHandler();
return (true);

"Back button" using getSupportActionbar and appcompat v7 toolbar

I'm using the new toolbar from the Appcompat V7 library and I'm making an application with navigation drawer and with fragments.
In some fragments I don't want to show the hamburger icon but the arrow instead... That is fine I did this in this way:
mDrawerToggle.setDrawerIndicatorEnabled(false);
mDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
My question is that: How or where i need to set up the home button lisener or what i need to listen for the "back" button ?
I want to call the main backpressed method and to set back the navigation drawer icon with the hamburger icon..
Add this method in onCreate():
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Then override the onOptionItemSelected() as below:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
You can do it like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
toolbar = (Toolbar)findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
setUpNavigationDrawer();
getFragmentManager().addOnBackStackChangedListener(backStackListener); // listen to the backstack of the fragment manager
}
Define the onBackSTackChangedListener:
private FragmentManager.OnBackStackChangedListener backStackListener = new FragmentManager.OnBackStackChangedListener() {
#Override
public void onBackStackChanged() {
setNavIcon();
};
}
Set the icon according to your fragment's backstack:
protected void setNavIcon() {
int backStackEntryCount = getFragmentManager().getBackStackEntryCount();
drawerToggle.setDrawerIndicatorEnabled(backStackEntryCount == 0);
}
Detect when the drawer icon is pressed:
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.isDrawerIndicatorEnabled() && drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case x:
return true;
default:
return false;
}
}
And handle the up button:
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
This works for me. Good luck.
Not sure if this works in OP's case, but in many cases this is probably the simplest option to implement Back button with the AppCompat Toolbar.
Skip all the setHomeButtonEnabled, setDisplayHomeAsUpEnabled and onOptionsItemSelected stuff, and related issues.
Instead, when initialising the Toolbar, simply set 1) navigation icon and 2) navigation OnClickListener for it:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (enableBackNavigation) {
toolbar.setNavigationIcon(R.drawable.ic_back);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
1- Create Toolbar layout;
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/dark_blue"
android:minHeight="?attr/actionBarSize"
local:popupTheme="#style/ThemeOverlay.AppCompat.Light"
local:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
2- Include this in your layout at the place where you want the toolbar to be.
3- Paste the following code in your activity.(extends ActionBarActivity)
private Toolbar mToolbar;
//For Toolbar (Action bar) start
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
mToolbar.setNavigationIcon(R.drawable.ic_back_arrow);
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
getSupportActionBar().setTitle("Event Details");
//For Toolbar (Action bar) end
4- change the back click icon to whatever you want.
activate the back button:
getActionBar().setDisplayHomeAsUpEnabled(enable);
and listen for clicks in onBackPressed()
Obviously your activity must extend ActionBarActivity
Simply you can set Navigation icon and make sure you are setting setNavigationOnClickListener() after setting setSupportActionBar(toolbar)
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_arrow_back));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
in manifest add these lines under the activity you want the back arrow working
android:parentActivityName="Your parent activity name"
Add setDisplayHomeAsUpEnabled(true)
Toolbar toolbar = findViewById(R.id.toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
Handle the back button
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}

Categories

Resources