Android Back Button functionality - android

I'm little bit fed up with the device back button functionality.
I have two activities. From 1st I go to 2nd and display one item through array in ListView and when I presses the back button i came back to 1st activity.
when I again go to 2nd activity to display the item once again it showing me the previous items at 1st row and then the same item in the second row as well.
Means it is not removing the previous item when i presses the back button.
I have used:
public void onBackPressed ()
{
for(int i=0; i<sub_categories.length;i++)
{
sub_categories[i]="";
}
Log.d(this.getClass().getName(), "*****************back button pressed");
}

I'm not entirely sure what you are trying to do, since you are not describing where you actually delete your item.
If you really always want to delete the item you have highlighted upon leaving activity no 2, you could delete it in onStop().
If you don't want to remember the state when leaving the activity you should set android:saveEnabled="false" in your layout manifest.

You need to notify the adapter that the data has changed using notifyDataSetChanged. And the adapter will tell the ListView to update it's view.

Here is how you can run code on key press:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
Log.d("BACK KEY PRESSED");
}
return super.onKeyDown(keyCode, event);
}
After returning to an activity, use notifyDatasetChanged in the activity onResume() to update the list.

Related

Show dialog on back pressed inside fragment

I've an activity and inside it a fragment.
What's the right procedure to ask for saving data (via a dialog) before exiting the activity?
User press back
Activity notify the fragment via interface onBackPressed
Fragment show dialog where user can choose to save/unsave data
User choose an option in the dialog
Fragment notify activity that calls super.onBackpressed()?
I'm not sure about point 5, because at point 2. I've to avoid default behaviour, instead at 5. I've to call super.
I need to mantain the save business logic inside the fragment.
P.S. the result is something like when FB app ask you on exit, to save or delete a post that is still a draft.
What you described works. Alternatively, for step 5, you can simply do
getActivity().finish;
if the user confirms exiting.
In the onCreateView() of the fragment, right before you return the view, add a listener to it:
v.setOnKeyListener( new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if( keyCode == KeyEvent.KEYCODE_BACK){
//do your stuff
}
return false;
}
});
return v;

Android: onBackPressed() not being called when navigation drawer open

I have a main activity that is situated with two navigation drawers. The left one is always accessible, but the right one is used for displaying some necessary lists and performing certain actions. When I have certain fragments loaded into the center FrameLayout of the activity they have actions that require the right drawer be opened and an item be selected. All of this is working great, but I want to make sure that when either the back button is pressed or the screen is clicked outside the drawer that the drawer is closed, locked and the fragment loaded in there is removed. I should also mention that this right drawer holds a FrameLayout and relies on fragments.
In my main activity this is what I'm calling:
#Override
public void onBackPressed(){
Log.d(TAG, "onBackPressed() called");
if(drawerLayoutRight.isDrawerOpen(drawerFrameRight)){
Log.d(TAG, "----------------------");
drawerLayoutRight.closeDrawer(drawerFrameRight);
drawerLayoutRight.setDrawerLockMode(1, drawerFrameRight);
ExcerciseList fragment = (ExcerciseList) getFragmentManager().findFragmentById(R.id.right_drawer);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.remove(fragment).commit();
} else {
super.onBackPressed();
}
}
I also tried:
public boolean onKeyDown(int keyCode, KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_BACK) {
Log.d(TAG, "onKeyDown called");
return true;
}
return super.onKeyDown(keyCode, event);
}
But this hasn't worked either. Whenever I click the back button the drawer will close, but neither of these methods would be called. But once the drawer is closed, if the back button is pressed these methods will be invoked. I was also wondering if anyone knew of a simple way to handle a click outside of the drawer. I figure I could make a custom DrawerLayout and override drawerClose() or check the coordinates that are clicked on a touch event. Just curious if anyone has a simpler way.
Put this line into your code:
mDrawerLayout.setFocusableInTouchMode(false);
Then it will call your overwritten onBackPressed() when you press the back button.
Quoting myself from the question at Force EditText to lose focus when back pressed
"In my experience onBackPressed() (at least the default #Override one in an activity) will not normally fire when pushing the back button to close the keyboard. As far as I know it will only fire when a Back press would initiate a finish() on the current activity."
This probably applies the same way to the navigation drawer.
This is most likely due to the fact that the current "Activity" is not in focus when the drawer opens (same with the SoftKeyboard) so the #Override back button is not called.
I was able to solve my problem by using DrawerLayout.DrawerListener. This worked in my situation because when the back button was being pressed the drawer was still closing even though the method onBackPressed() wasn't being called.
#MH said, "The DrawerLayout (I assume that's what you're using) will consume the back button event if the drawer is opened."
Although in the documentation I could not find an explicit mention of this; there was some mention of the back button here. Unfortunately it was not of much help.
What #MH said explains why onBackPressed() was not being called when the drawer was opened, and why it was being called while it was closed.
drawerLayoutRight.setDrawerListener(this);
Where drawerLayoutRight is a DrawerLayout. And my listener looks like this:
#Override
public void onDrawerClosed(View arg0) {
if(drawerLayoutRight.getDrawerLockMode(drawerFrameRight)!= 1){
drawerLayoutRight.setDrawerLockMode(1, drawerFrameRight);
}
ExcerciseList fragment = (ExcerciseList) getFragmentManager().findFragmentById(R.id.right_drawer);
if (fragment != null) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.remove(fragment).commit();
}
}
onDrawerOpened(), onDrawerSlide() and onDrawerStateChanged() are all empty. Only one of my drawers is using the listener so I don't have to check the view.
Just simple overrede your activity or drawerlayout, will do.
#Override public boolean onKeyDown(int keyCode, KeyEvent event) {
if (KeyEvent.KEYCODE_BACK == keyCode
&& mDrawerLayout != null
&& mDrawerLayout.isDrawerOpen(leftDrawerView)) {
KeyEventCompat.startTracking(event);
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override public boolean onKeyUp(int keyCode, KeyEvent event) {
if (KeyEvent.KEYCODE_BACK == keyCode
&& !event.isCanceled()
&& mDrawerToggle != null
&& mDrawerLayout.isDrawerOpen(leftDrawerView)) {
mDrawerLayout.closeDrawers();
return true;
}
return super.onKeyUp(keyCode, event);
}
The problem, as #Alex Vasilkov indicated, seems to do something with the drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); method.
None of the suggestions above did work for me. So I wanted to write my own solution. I digged the source code of DrawerLayout Class and tried overriding onKeyDown and onKeyUp methods, but the Back Button click is not getting triggered at all, if the Lock mode is LOCK_MODE_LOCKED_CLOSED. I think this is a bug.
So in my case, I needed to lock left navigation drawer only, not the right one. And I ended up calling drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED, Gravity.START); this method to lock my left navigation drawer instead of calling drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); this method, which locks both of the drawers and causes this back button bug.
So as a summary, drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); disables back button click somehow. Maybe only if you have two navigation drawers.
After adding this line back button will manage to close DrawerLayout.
mDrawerLayout.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
I had a very similar issue with an empty list in a fragment (wouldn't respond to back button press when the list was empty) and some of the solutions mentioned here helped me solving my issue.
The fragment causing the issue with the "onBackPressed()":
<TextView
android:id="#android:id/empty"
... />
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
The issue is similar in that when the list returned by the adapter is empty (#android:id/empty), the first view (TextView) doesn't seem to be "considered" as a focusable/focused view by Android (whereas the second view - ListView - is).
So pressing the back button wouldn't be registered by the view currently displayed and wouldn't be caught by my custom code in the fragment (instead closing the activity directly).
In my case, adding the following to onCreateView solved my issue (and allowed the back button press to be caught by the fragment even when the list is empty):
View view = inflater.inflate(R.layout.fragment_content, container, false);
view.setFocusableInTouchMode(true);
view.requestFocus();
I know it is a bit late but still... this answer will help others
#Override
public void onBackPressed()
{
if (mDrawerLayout.isOpen())
mDrawerLayout.close();
else
super.onBackPressed();
}

How can I refresh a previous activity after the back button is pressed?

I am building an alarm application. I currently have a ListActivity which display the list of alarms and another activity which changes the time of a particular alarm. My problem is, when I decide to enter into the activity to change the time of an alarm and then I press the back button, it does not refresh. However, I've implemented a button that redirects back to the ListActivity and if I press it, the list of alarms are refreshed. How can I, after pressing the back button, refresh the list of alarms?
You should probably override your onResume() to check if the list of alarms have been refreshed so that whenever you come to/come back to your ListActivity, it'll get updated.
In your alarm list activity
use
public void onRestart() {
// reload your list items if changed and adapter.notifydatastatechange();
}
If you done this in onResume then its call two times first when your activity start n 2nd when your activity restart.
here is the code.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Intent a = new Intent(this,yourback.class);
a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(a);
return true;
}
return super.onKeyDown(keyCode, event);
}
i always use this when back is listview.
I am using following one.
Intent intent = new Intent(CurrentActivity.this, PreviousActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
CurrentActivity.this.finish();

List_view getting items back

I have 3 different function in an activity namely , main category,sub_category and list of items. By clicking main category it displays sub_category and same like list of item.I want to give back option, in order to view back functions. for example at the time of viewing list_of item by clicking back option, i want to show sub_category and by clicking back button from sub_category i want to display main category. I dont know how to do this. All the above function are reside in one class. can anyone give solution for this..??
Override onKeyDown function to handle back key event.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if((keyCode == KeyEvent.KEYCODE_BACK)) {
Log.d(this.getClass().getName(), "back button pressed");
// invoke your navigation function
// return true; - to prevent this event from being propagated further
}
return super.onKeyDown(keyCode, event);
}

Help prevent Back button from closing sub-activity

I have a main activity. It's main purpose is to handle Tab menu. If a user click a tab it'll load another activity as a sub-activity, still showing the tab menu. I am using Intent to do this:
setContent(new Intent(this,B.class))
This sub-activity has an onclick function as well. If the user clicks one of the links it'll load xml layout file using setContentView command:
setContentView(R.layout.B1);
Now, when the back button is pressed while xml file is loaded, it'll close the entire application. Is there a way to prevent this, say, return to the sub-activity or the main activity?
thanks for all your help.
You should override the onBackPressed method in your activity or sub activity:
#Override
public void onBackPressed() {
//TODO Do your task here
}
In your sub activity you should override the fallowing:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) //Override Keyback to do nothing in this case.
{
return true;
}
return super.onKeyDown(keyCode, event); //-->All others key will work as usual
}

Categories

Resources