What function runs when we press back arrow? - android

I have an activity that when the user press back arrow doing some thing.
When you press the back button on the phone, it does the finish () method, but it doesn't happen when you press the back arrow. How to fix it?
I'm sorry for the grammatical errors. I would be happy if you remind me of the bad ones.

are you looking for
Xamarin.Android:
public override void OnBackPressed()
{
// do something on backbutton pressed
}
Java:
#Override
public void onBackPressed()
{
// code here to show dialog
super.onBackPressed(); // optional depending on your needs
}

If you want the same behavior for the back button. Add this code.
Java Code
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == android.R.id.home) {
YourActivity.this.onBackPressed();
}
return super.onOptionsItemSelected(item);
}
Kotlin Code
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
this#YourActivity.onBackPressed()
}
return super.onOptionsItemSelected(item)
}

Related

Back Arrow press exiting the App in Android [duplicate]

I want to customize the activity back button in action bar, not in hard key back button. I have overriden the onBackPressed() method. It works with my emulator back button, but not with action bar back button.
I want it to happen with action bar. How can I do this?
Here is my code:
#Override
public void onBackPressed() {
Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
return;
}
I have used this toast whether back pressed is working or not but the actual implementation changes like to move back to previous activity. But this is not working with the button present on top of action bar (besides title of the activity).
Please any one could specify me the problem.
I think you want to override the click operation of home button. You can override this functionality like this in your activity.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
If you want ActionBar back button behave same way as hardware back button:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}
return false;
}
Two things to keep in mind that the user can either press back button or press the actionbar home button.
So, if you want to redirect him to the same destination then you can do this.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return false;
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
startActivity(intent);
finish();
}
This will take the user to the intent pressing either key or the action bar button.
Sorry mine is a late answer, but for anyone else arriving at this page with the same question, I had tried the above:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
...
if (item.getItemId() == android.R.id.home) {
....
}
....
}
but this failed to catch the "Back" button press.
Eventually I found a method that worked for me on https://stackoverflow.com/a/37185334/3697478 which is to override the "onSupportNavigateUp()" as I am using the actionbar from the "AppCompatActivity" support library. (There is an equivalent "onNavigateUp()" for the newer actionbar/toolbar library.)
#Override
public boolean onSupportNavigateUp(){
finish();
return true;
}
and I removed the "android:parentActivityName=".MainActivity" section from the manifest file.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return true;
}
(1) Add Parent activity for your child activity (AndroidManifest.xml)
<activity
android:name=".ParentActivity" />
(2) override the onSupportNavigateUp method inside the child activity
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return false;
}
I have achieved this, by using simply two steps,
Step 1: Go to AndroidManifest.xml and in the add the parameter in tag - android:parentActivityName=".home.HomeActivity"
example :
<activity
android:name=".home.ActivityDetail"
android:parentActivityName=".home.HomeActivity"
android:screenOrientation="portrait" />
Step 2: in ActivityDetail add your action for previous page/activity
example :
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
If you want to return to the previous instance of an Activity by pressing of ActionBar home button, without recreating it, you can override getParentActivityIntent method to use the one from the back stack:
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public Intent getParentActivityIntent() {
return super.getParentActivityIntent().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
EDIT:
Also you can achieve the same result by
setting the launchMode of your parent activity to singleTop.
So setandroid:launchMode="singleTop" to parent activity in your manifest.
Or you can use flag FLAG_ACTIVITY_CLEAR_TOP with the UP intent.
reference: Providing Up Navigation
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
return true;
}
//noinspection SimplifiableIfStatement
if (id == R.id.signIn) {
return true;
}
return super.onOptionsItemSelected(item);
}
///////////////////
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
There are several ways how to set up back button in bar:
1) method .setDisplayHomeAsUpEnabled(true); will do it, and then you can simply override android.R.id.home
2) adding <meta-data android:name="android.support.PARENT_ACTIVITY" android:value="my.package.parrent" /> in Android Manifest, but in this case you can not override android.R.id.home in OnOptionsMenuSelected.
.. for those who wonder why it doesn't work for them...

How to handle ActionBar's icons visibility when using SearchView

Well, what I want is to:
Initialize ActionBar with all items, except "searchSettings";
When click on the Search icon, searchSettings appears and the rest of the icons disappear;
When close the search EditText (pressing device's back button or ActionBar's back button), ActionBar returns to its original state (all icons appearing, except "searchSettings").
My actual code is the following:
(I've imported android.support.v7.widget.SearchView instead of android.widget.SearchView. When I was using android.widget.SearchView this worked fine but other things don't)
private MenuItem searchIteam, searchSettings;
private SearchView searchView;
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menuMain);
searchItem = menu.findItem(R.id.search);
searchSettings = menu.findItem(R.id.action_searchSettings);
searchView = (SearchView)MenuItemCompat.getActionView(item);
searchSettings.setVisible(false); // hide searchSettings Item when Menu is created
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
(...)
return false;
}
});
// Detect SearchView icon clicks
searchView.setOnSearchClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setItemsVisibility(menuMain, item, false);
searchSettings.setVisible(true);
}
});
// Detect SearchView close
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
#Override
public boolean onClose() {
supportInvalidateOptionsMenu(); //shouldn't this reload the Action Bar as it was when onCreate?
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
private void setItemsVisibility(Menu menu, MenuItem exception, boolean visible) {
for (int i=0; i<menu.size(); ++i) {
MenuItem item = menu.getItem(i);
if (item != exception) item.setVisible(visible);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
supportInvalidadeOptionsMenu();
super.onBackPressed();
}
This code doesn't work, when I press "back" first time, it only closes the Search's EditText and the icons don't change. If I press back again, the Activity goes a level up but I can see the icons getting as the beginning (getting as they should when I pressed "back" for the first time) a little while before the Activity close...
--- EDIT ---
Currently, if I click on Search ActionBar Icon, and then begin to press "Back Button" repeatedly, the following happens:
1st pressing: the keyboard hides, but the search EditText is still open;
2nd pressing: the searching ends (search EditText closes and the normal activity's content is shown);
3rd pressing: the activity closes.
Then, for testing purposes, I did this:
boolean pressed1, pressed2, pressed3;
searchView.setOnSearchClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pressed1 = false;
pressed2 = false;
pressed3 = false;
setItemsVisibility(menuMain, item, false);
searchSettings.setVisible(true);
}
});
#Override
public void onBackPressed() {
if (!pressed1) {
pressed1 = true;
}
else if(!pressed2) {
pressed2 = true;
}
else if(!pressed3) {
pressed3 = true;
supportInvalidateOptionsMenu();
}
else {
super.onBackPressed();
}
}
And now, what happens is:
1st pressing: the keyboard hides, but the search EditText is still open;
2nd pressing: the searching ends (search EditText closes and the normal activity's content is shown);
3rd pressing: nothing happens;
4th pressing: nothing happens;
5th pressing: the ActionBar reloads as I wanted;
6th pressing: the activity closes;
--- EDIT 2 ---
Then I've changed to this:
#Override
public void onBackPressed() {
if (!pressed1) {
pressed1 = true;
onBackPressed();
}
else if(!pressed2){
pressed2 = true;
onBackPressed();
}
else if(!pressed3){
pressed3 = true;
supportInvalidateOptionsMenu();
}
else {
super.onBackPressed();
}
}
What is happening now is:
1st pressing: the keyboard hides, but the search EditText is still open;
2nd pressing: the searching ends (search EditText closes and the normal activity's content is shown);
3rd pressing: the ActionBar reloads as I wanted;
4th pressing: the activity closes;
--- EDIT 3 --- (SOLUTION) ---
I guess that the methods setOnSearchClickListener and setOnCloseListener are from android.widget.SearchView... As I've imported android.support.v7.widget.SearchView instead, I've changed them to:
MenuItemCompat.setOnActionExpandListener(searchItem,
new MenuItemCompat.OnActionExpandListener() {
#Override
public boolean onMenuItemActionExpand(MenuItem menuItem) {
setItemsVisibility(menu, searchItem, false);
return true;
}
#Override
public boolean onMenuItemActionCollapse(MenuItem menuItem) {
supportInvalidateOptionsMenu();
return true;
}
});
Now it's working just fine (:
I hope I get you right: the first time you press BACK, the keyboard gets hidden. The second time you press BACK, the app quits.
If this is the case, then everything works fine. Becuase this is what super.onBackPressed() is supposed to do. It will try to hide the keyboard if it's shown. If not, it will try to go the previous activity. If there is none, it will quit the app.
So what you need to do is play with the onBackPressed() method. Basically, you don't necessarily need to call the super method if you are sure what you should do.
#Override
public void onBackPressed() {
if ( isSearching) {
supportInvalidadeOptionsMenu();
isSearching = false;
} else {
super.onBackPressed();
}
}
So now, when never you press BACK button, the activity will check if isSearching, and decide to re-render the action bar or take its normal actions as usual.
You'll need to add some logic to set the boolean flag isSearching, for example, set isSearching to true when clicking the Search.
I 'm not sure if supportInvalidadeOptionsMenu() would reset your action bar. Anyway, you can adjust the visibility for each view instead.

simulate up when back button is pressed

I'm working on an android app and recently, I discovered that the default back button onBackPressed() produces a back behaviour, while the getSupportActionBar().setDisplayHomeAsUpEnabled(true) produces an up behaviour. And the two have significant differences.
I was wondering if I can simulate the up behaviour when I press the hardware back button, so that it navigates up instead of back.
Thanks.
You can do this.
#Override
public void onBackPressed() {
NavUtils.navigateUpFromSameTask(this);
}
You can do this
Overide onOptionsItems Selected
Create a switch case of android.R.id.home
Call method onBackPressed();
here is the code
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
default:
return super.onOptionsItemSelected(item);
}
}

How can I add an Action after clicking on an ActionBar's Button?

I want to add a new button to the ActionBar. When I click it, it does a specific Action. So I don't want a button that, after being pressed, opens a sub-menu (like the classic 3-dot menu).
I created a new button, this:
<item android:id="#+id/action_refresh"
android:icon="#drawable/refresh"
android:title="#string/refresh_string"
android:showAsAction="always"/>
and it's shown on the ActionBar, but if I click it, naturally, it doesn't do anything.
How can I manage to get an Action just pressing it?
Thanks!
You Need to override onOptionsItemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_refresh:
//do your stuff
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Same as Homo sapiens's answer, but with an if-structure.
Add this method to your Activity class:
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getItemId() == R.id.action_refresh)
{
// do your stuff
return true;
}
else if (item.getItemId() == R.id.otherItem)
{
// do other stuff
return true;
}
// ...
else
{
return super.onOptionsItemSelected(item);
}
}

Android Back Button to specific activity

When I click the back button Android goes to the previous activity.
Is it possible to set for every activity a custom (back) activity
or to set the back button to the home menue of the app?
Help or hints would be great :)
You will have to override onBackPressed() from your activity:
#Override
public void onBackPressed()
{
super.onBackPressed();
startActivity(new Intent(ThisActivity.this, NextActivity.class));
finish();
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent i = new Intent(this.class, yourcustomclass);
startActivity(i);
finish();
}
}
Yes it's possible, just add this method to your activity:
public void onBackPressed() {
//Do the stuff you want on backbutton pressed.
}
Yes you should #override the onBackPressed() function and create an Itent to go wherever you want.
You can override the
#Override
public void onBackPressed(){
}
If you need to go back what ever activity, when click on ActionBar back arrow(Home). overide onSupportNavigateUp()
#Override
public boolean onSupportNavigateUp() {
//onBackPressed(); //this will be go to parent activity
//******************//
// Your intent here //
//******************//
return true;
}

Categories

Resources