I have a back button in one activity and when I tap on it to return to the parent activity it will reset the parent activity. It's like onCreate() is being called again. I'm not sure why that is because when you tap on the back button it just calls finish() to exist the activity I'm currently in.
Here is how I'm declaring the toolbar:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_item);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
if(getSupportActionBar() != null)
{
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
This is what happens when you tap on the button:
public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getItemId()==android.R.id.home)
{
finish();
}
return super.onOptionsItemSelected(item);
}
The strange this is that when I hit the save button I return to the parent activity without any reset. So I'm not sure why this is happening.
You need to return true or else it will always call the onCreat() method. Also, you can create an "empty" intent and just not process it on the activity you return true.
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getItemId()==android.R.id.home)
{
Intent intent = new Intent();
setResult(Intent_Constant.TAPPED_BACK_BUTTON, intent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
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);
}
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);
I have an app with tab navigation between fragments. One of these fragments has an option to open a new activity. When I use the built in device back button from this activity it goes back to the tabbed activity with the previous fragment tab selected.
I have added a back button to the action bar of an activity in my app by using:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
and setting the parent activity in the manifest, but this button always navigates back to the first tab of the parent activity, rather than the one that was previously visible.
How can I make this back button behave in the same way as the device back button?
Do something like this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
onBackPressed() method:
#Override
public void onBackPressed() {
super.onBackPressed();
}
Handle back event in this manner
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
in back press method
#Override
public void onBackPressed() {
Intent intent = new Intent(SecondActivity.this,TabbedActivity.class);
intent.putExtra("IsBack",true);
startActivity(intent);
}
in your tabbed activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabs);
if(getIntent().getExtras().getBoolean("IsBack")){
//navigate to your desire fragment
}
}
with the help of these Android Docs.I am trying to do a action bar Back button.I get an Action Bar Back Button like these below image:
Output:
But My problem is After watching the Gallery images I press the action bar back button.
Then it is not working.But it have to go back to previous page.
Listed below are the codings.
GalleryActivity.java:
import android.app.ActionBar;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.view.MenuItem;
import com.fth.android.R;
public class GalleryActivity extends FragmentActivity {
private int position;
private static String id;
private static String name;
private DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery);
position = getIntent().getExtras().getInt("position");
id = getIntent().getExtras().getString("id");
name = getIntent().getExtras().getString("name");
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager());
// Set up action bar.
final ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
// getActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME|ActionBar.DISPLAY_USE_LOGO|ActionBar.DISPLAY_HOME_AS_UP);
// Set up the ViewPager, attaching the adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent upIntent = new Intent(this, HomeActivity.class);
upIntent.putExtra("position", position);
if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
TaskStackBuilder.from(this)
.addNextIntent(upIntent)
.startActivities();
finish();
} else {
NavUtils.navigateUpTo(this, upIntent);
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
GalleryDetailFragment.java:
import com.sit.fth.model.GalleryDetail;
import com.sit.fth.util.APIServiceHandler;
import com.sit.fth.util.AppConstants;
import com.sit.fth.util.AppPromoPager;
public class GalleryDetailFragment extends BaseFragment implements
PromoPagerListener {
private TextView countView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.setHasOptionsMenu(true);
id = getArguments().getString("id");
name = getArguments().getString("name");
View view = inflater.inflate(R.layout.app_pager, null);
return view;
}
}
Anybody can help me if you know how to solve these.Thank You.
I solved these problem by adding the below coding in GalleryActivity.
ActionBar actionBar;
actionBar=getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
In MainActivity:
Previously,
public class HomeActivity extends BaseActivity
Then I change into
public class HomeActivity extends FragmentActivity
In GalleryFragment:
I use Intent to pass it to the GalleryActivity.
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Gallery gallery = (Gallery) arg0.getAdapter().getItem(arg2);
Intent intent = new Intent(getActivity(), GalleryActivity.class);
intent.putExtra("position", position);
intent.putExtra("id", gallery.getGalId());
intent.putExtra("name", gallery.getAlbumTitle());
startActivity(intent);
// mCallback.OnGalItemSelected(gallery.getGalId(),gallery.getAlbumTitle());
}
Please read this
you should have something like this:
<activity
android:name="com.sit.fth.activity.HomeActivity"
android:screenOrientation="portrait">
</activity>
<activity
android:name="com.sit.fth.activity.GalleryActivity"
android:screenOrientation="portrait"
android:parentActivityName="com.sit.fth.activity.HomeActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.sit.fth.activity.HomeActivity"/>
</activity>
then calling NavUtils.navigateUpFromSameTask(this) will cause navigating to parent activity (HomeActivity).
You need to call setDisplayHomeAsUpEnabled(true) method in the onCreate method and override onSupportNavigateUp() and call onBackPressed() in it as below. That's it. done :)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
You have just to add the following line to the activity in the manifest.xml. The parent activity is the activity to which you want to go back.
android:parentActivityName=".activities.MainActivity"
Try like
First of all you need to use addToBackStack() before commit() for Fragments
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
if(getSupportFragmentManager().getBackStackEntryCount()>0)
getSupportFragmentManager().popBackStack();
return true;
}
return super.onOptionsItemSelected(item);
}
Best and easy answer is add the parent activity name in Manifest file, so Actionbar back button will work.
For that under that Activity tag of Manifest File use
android:parentActivityName=".MyCustomParentActivity"
if the home button is shown. you should add an action to the home button through onOptionItemSelected fun (arrow in your case) by default there's no action. so it's totally normal that it's not working. Please add this fun to your activity :
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when {
item.itemId == android.R.id.home -> {
finish()
true
}
else -> super.onOptionsItemSelected(item)
}
}
None of the answers provided here worked for me. I had to put the switch inside the onMenuItemSelected method. I'm aware this is not what is stated in the Android documentation, but still, it worked, so I just thought I'd leave this here for people who run into the same issue. My problem involved an Activity instead of a Fragment though, but that should be pretty much the same.
class FooActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return false;
}
}
To me, I had to set mDrawerToggle.setToolbarNavigationClickListener(...) to a listener that triggers the back action. Otherwise it does nothing. This is what the source code of ActionBarDrawerToggle looks like:
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mDrawerIndicatorEnabled) {
toggle();
} else if (mToolbarNavigationClickListener != null) {
mToolbarNavigationClickListener.onClick(v);
}
}
});
So the default behaviour is actually to call our listener, and not do any magic on its own.
Use on SupportNavigateUp() method and call onBackPressed in this method.
onCreate
{
...
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
resetActionBar();
...
}
public void resetActionBar()
{
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
int count = fm.getBackStackEntryCount();
if(count == 0) {
// Do you want to close app?
showDialog();
}else{
super.onBackPressed();
}
}
#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();
Log.i("coming", "comming");
//noinspection SimplifiableIfStatement
if(id==android.R.id.home){
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
onBackPressed();
else
drawerLayout.openDrawer(navigationView);
return true;
}
return super.onOptionsItemSelected(item);
}
Here is one more thing to check for in case the other answers here (or here or here or here) don't work.
I had copied some code from another activity that disabled the menu. Deleting this method (and applying the solutions given in the others answers) allowed the up button to work.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// hide the menu
return false;
}
In my case I had overridden the onCreateOptionsMenu method and I forgot to call super at the end.
Tool bar enable back button for Kotlin binding
setSupportActionBar(binding.toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_times_ic)