Back Button in ActionBar of App - android

Generally switching from one activity to another activity hamburger icon is replaced with back arrow. I want to control the functionality of that arrow. I have seen many contents here but most of them were related to hardware's back button. How can I control that?
I am trying the functionality in case of fragments. Also I have Navigation drawer attached with the hamburger icon.
I tried this-
if(id == android.R.id.home){
getSupportFragmentManager().beginTransaction().replace(R.id.main_container, new AmbulanceMap()).commit();
getSupportActionBar().setTitle("Book A Ride");
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
}
but doesnt work as I hoped.
I want my back button to change the fragmentto previous fragment.

I had the same problem once. Just like you, things like checking if Android.R.id.home is clicked didn't work.
But I solved it using that:
Set navigation listener to toolbar:
toolbar.setToolbarNavigationClickListener(v -> onBackPressed());
If it should be within fragment:
Create an public method in activity.
In fragment's onAttach (or later) cast getActivity() to your activity and call method you was defined previously.
Example:
// YourActivity
public void setHomeListener(OnLickListener listener){
toolbar.setToolbarNavigationClickListener(listener);
}
//Fragment's onCreate
((YourActivity)getActivity()).setHomeListener(v -> onBackPressed());
//Fragment's onDestroy
((YourActivity)getActivity()).setHomeListener(null);
And, of course, set home us up enabled to show back arrow.
EDIT
if you don't use labmdas u should use:
(YourActivity)getActivity()).setHomeListener(new OnClickListener() {
#Override
public void onClick(View v) {
YourFragment.this.onBackPressed();
}
});

The back button of the ActionBar is a menuItem so you need to override onOptionsItemSelected like this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
//Your back button logic here
break;
}
return true;
}
Also donĀ“t forget to add getSupportActionBar().setDisplayHomeAsUpEnabled(true); after setting the Toolbar

Related

Is it possible to set different actions for floating action button in differet fragments?

I am working or an app where I have 4 fragments in viewpager and floating action button (fab). When I click on fab there appear 3 subfabs. Each of them start different activities where user can search data from different fragments. Is it possible to set fab so that if I click on it while I'm in first fragment it'll open an activity for searching inside this fragment, onClick inside second - search for second and etc. The issue is that now clicking on sub fab while I'm in some fragment I can search data from another fragment too and it's a bit weird. I understand question is kinda strange, if something is unclear I'll explain further
You can make FAB button public and implement onClick listener in each fragment.
You should override setUserVisibleHint and put your code onResume so getActivity() will not return null. Fab button will have different actions in different fragments.
Here's an example, inside each fragment when you want Fab click listener:
#Override
public void setUserVisibleHint(boolean visible)
{
super.setUserVisibleHint(visible);
if (visible && isResumed())
{
onResume();
}
}
#Override
public void onResume()
{
super.onResume();
if (!getUserVisibleHint())
{
return;
}
MainActivity mainActivity = (MainActivity)getActivity();
mainActivity.fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Do what you want
}
});
}
You can check in onclick method of floating action button which fragment is currently opened and calling it.
Call findFragmentById() on FragmentManager and determine which fragment is in your R.id.frameTitle container.

Android Toolbar with both home and back button

Is it possible to display both home icon and back icon in the toolbar?
1) Is it possible change the order of display of back button icon and home icon.
Currently it displays the arrow button first and then the logo (home button)
2) Second requirement is to clear the activity stack on clicking the home icon and going back to previous screen in case of back button.
I have the following code which will display a arrow back key and home icon which is set as logo. Is it possible to handle click events on both these icons:
Toolbar toolbar = (Toolbar)findByViewID(R.id.toolbar);
toolbar.setNavigationIcon(R.drwable.btn_back);
setSuppportActionBar(toolbar);
getSupportActionBar().setLogo(R.drawable.home_icon);
getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
I am able to handle to the click on arrow icon by handling it in onOptionsITemSelected method.
Is there a way to handle click on logo icon?
My idea is to use the home button click to clear the stack of activities and use the back button to navigate back to previous screen.
I tried with
toolbar.setNavigationOnClickListener()
but it has no effect on back button click.
Handling android.R.id.home works when handled in
onOptionsItemSelected()
For navigating back. This worked for me.
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case android.R.id.home:
Intent homeIntent = new Intent(this, HomeActivity.class);
homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(homeIntent);
}
return (super.onOptionsItemSelected(menuItem));
}
try with this
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
getActivity().finish();
}
return true;
}
});
Design our custom layout as a separate "toolbar_content.xml" and include this layout inside toolbar tag in your "main_layout.xml".
Write click listeners for your items in "toolbar_content.xml" in your base activity so that listeners will be available thru out the app.

Android activity to a fragment control transfer

I am creating an android application with three tabs using PageSlidingtabStrip as a library to create a swipe view.And it has three fragments.Each fragments has a list view.When the item of the listview is clicked it opens an activity and display the details.
The problem is how can i come back to the fragment in the main screen using back button in actionbar in the activity
And how can i go to the corresponding Fragment(Tab)
Try something like this :
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent intent = new Intent(YourCurrentClass.this , ClassThatYouWantToGo.class);
startActivity(intent)
}
Or actually like #TommyTopas said, you can just Override onBackPressed and put this.finish();.
EDIT
As I've understood you want to use a button on your AcitonBar, then you have tod o something like this :
First set the HomeButton enabled doing :
getActionBar().setDisplayHomeAsUpEnabled(true); Then Override onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// or onBackPressed();
this.finish()
}
return true;
}
As I understand, when you return to the "Tab" Activity, you want to display the same tab in which the list item had been clicked. What you can do is, when a list item in any tab is clicked, save the tab number in onSavedInstanceState(), and when the Activity is recreated, then set the previously selected tab (if one was selected previously). You will get the savedInstanceState that you saved in onSavedInstanceState() back in the onCreate() of the same Activity.
You can provide an Up navigation by writing getActionBar().setDisplayHomeAsUpEnabled(true); and then in the onOptionsItemSelected method in the activity, if the item's id is android.R.id.home call the activity's method onBackPressed(); which will close your current activity and come back to your fragment

Making back button and action bar back the same

For example, I have 2 activities which are named Main and Photos. I start Photos from Main. When I press back button when Photos activity opened, my navigation drawer menu is still selected. However, if I press back menu on action bar, Main activity refreshes, so selection disappears. I want to apply action bar back's event on back button. How can I do?
Its better to make your action bar button implement androids back buttons action rather than vice-versa, however, it can be done.
// Newer, but Im not sure what API version it came in
#Override
public void onBackPressed() {
//super.onBackPressed();
mMyAbBackBtn.callOnClick();
}
// Older, still supported
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (KeyEvent.KEYCODE_BACK == keyCode) {
mMyAbBackBtn.callOnClick();
return true; //handled
}
return super.onKeyUp(keyCode, event);
}
The "back button on action bar" is actually called an Up button. Just to clarify the differences: the Back button returns you to the previous activity (this could bring you to a different app) while the Up button will return you to the previous activity in the current application.
I'm quite confused how you have an Up button and a navigation drawer at the same time, would you put up some screenshots?
Assuming your "navigation drawer menu" isn't a native part of android that you're talking about, I don't recommend overriding your Back button to get your desired behavior.
Instead consider overriding onActivityCreated or onResume:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(); // don't restore the state
// alternatively:
// super.onActivityCreated(savedInstanceState); // you may have other things you
// want to preserve
// unSelect(); // your code to unselect whatever your navigation menu drawer is
}
#Override
public void onResume()
{
super.onResume();
unSelect(); // your code to unselect whatever your navigation menu drawer is
}

Creating custom back button in android

I have an application that has a menu and depending on what button you press in the menu a new activity is opened. I want to have a back button on every screen that will bring you to the previous screen so I'm wondering how do I go about this?
Here is some code I have used that works:
backButton = (ImageButton) findViewById(R.id.back_button);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
However its not good programming practice for me to put this code in all my activities. How do I go about creating some kind of stack that saves all the pages viewed and using that to return to the previous page?
I have to put a back button in my application so I cannot use the existing one in the ActionBar.
just an Idea
Create a baseClass which extends Activity. In there declare
#Override
public void onClick(View v) {
super.onBackPressed(); // or super.finish();
}
In all activity extend this Base Class. And in every layout in the button put
android:onClick="onClick"
And to make the xml design of button reusable create it in a separate xml. and add it using <include/>
Have you tried using action bar in your activity ? use in every activity
ActionBar actionBar = getSupportActionBar();
if(actionBar != null){
actionBar.setTitle(getResources().getString(R.string.app_name));
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setIcon(R.drawable.app_icon);
}
and handle in
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
I would suggest against having a custom back button. Android has a hardware back button. Pressing the haradware back button will navigate to the previous.
I don't think you need a custom back button. I don't think its a good programming practice to override the default behaviour.
You create a backbutton in your activity and implementing the functionality as you have done above. Still the user can use the hardware back button for the same functionality. So you would be providing the same functionality which is redundant.
There is a hardware back button on all android devices, and it does exactly what your lines of codes do, unless overridden to do something else.
You can refer to this answer as well.
I had a similar issue where I was using a back button "Cancel" and a home screen "homeActivity". I ended up solving it using this:
CancelButton = (Button) findViewById(R.id.cancel_button);
CancelButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Intent homeActivity = new Intent(getApplicationContext(), DeviceListActivity.class);
startActivity(homeActivity);
finish();
}
});
In kotlin
backButton!!.setOnClickListener(View.OnClickListener {
onBackPressed()
})

Categories

Resources