Help prevent Back button from closing sub-activity - android

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
}

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;

Fragments, How to Navigate back to the previous Fragment, from the current Fragment?

I am using Fragment A,Fragment B .. and so on. i want to navigate back to the previous Fragment, from the current Fragment.
I want to use Back Button in Mobile to get back navigation.
How can i do this ? OR i have to make Back button in layout xml.
i tried below code,
fTransaction.add(R.id.container, nF).addToBackStack(null).commit();
when i pressed Back Button in Mobile , it restarts the App.
To go back to previous fragment using phone's back button you should override onKeyDown() mehtod.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if(keyCode == KeyEvent.KEYCODE_BACK)
{
getFragmentManager().popBackStack();
return true;
}
return false;
}
When replacing a fragment use replace instead of add and then addToBackStack:
fTransaction.replace(R.id.container, nF).addToBackStack(null).commit();
Try this:
fTransaction.addToBackStack(null).add(R.id.container, nF).commit();

How to handle back button using view pager?

I am having two fragments Frag A and Frag B which are rendered using view pager .
If user has swiped from A to B then presses back button(when in B) then user should go to A instead of coming out of view pager . How can we achieve this ?
Adding transaction to backstack does not seem to help .
Thanks
You have to override the onKeyDown() method in the Activity.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
myViewPager.setCurrentItem(0, true);
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
This will capture the "back" button press event and send the user to the first item in the ViewPager.
There is also ViewPager#getCurrentItem() which can be used to go back only if the user swiped. An implementation like this:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && myViewPager.getCurrentItem() == 1) {
myViewPager.setCurrentItem(0, true);
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
would send the user back to the previous page only if the user was on the next page. Else, it will register the "back" normally and the user will exit as expected.
You may want the case in which the user goes back to the previous page (assuming you have more than two pages). In which case, you want to implement the ViewPager.OnPageChangeListener() and save the position every time onPageSelected(int position) is called. If you implement them in a stack, then you can pop them off every time the user presses "back". Once the stack is empty, exit the app.
EDIT
As correctly stated in the comments by Jade Byfield, a slightly easier way to do this would be to use onBackPressed() in the Activity. This will only work in API levels 5+.
#Override
public void onBackPressed() {
if(i_dont_want_to_leave) {
myViewPager.setCurrentItem(0, true);
} else {
super.onBackPressed(); // This will pop the Activity from the stack.
}
}
On the Android Docs page
https://developer.android.com/training/animation/screen-slide.html#viewpager
I found an example of handling ViewPager sliding and there's a method
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
super.onBackPressed();
}
else {
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
This selects a previous page or exits the current activity.
I think a better approach would be to delegate the back key handling to the respective fragments. I have used a CustomFragment which supports a method to handle the back key. All the Fragments will be extending from this CustomFragment.
public abstract class BackKeyHandlingFragment extends Fragment {
public abstract boolean handleBackKey();
}
Activity can delegate the backKey processing to current Fragment. Fragments can perform required actions in their respective implementation of handleBackKey method. The method can return true to tell activity not to process the back key. To go ahead with default back key action at Activity level, the method can return false.
public void onBackPressed() {
BackKeyHandlingFragment fragment = (BackKeyHandlingFragment) mSectionsPagerAdapter.getItem(mViewPager.getCurrentItem());
// Fragment should return boolean according to app requirements after processing back key
if (!fragment.handleBackKey()) {
super.onBackPressed();
}
}

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);
}

Why my activities are not performing my overridden back button event?

I want to send back my activity to starting one. Let me explain you.
I am using Main activity having 4 tabs, and each tabs has his own activity. Each activity in has more activities in it.
Problem starts when I click on 1st activity in my 1st tab. The next activity is independent. I create an intent of my next activity. In such case to prevent draw my tab-bar layout in that new activity. I use my existing activity layout, remove all the view in it. Then i put new activity in it.
e.g..
contentViewLayout.removeAllViews();
View view = activityManager.startActivity(id, intent).getDecorView();
contentViewLayout.addView(view, contentViewLayoutParams);
Its done. But problem arise when device BACK button pressed. Because new activity is starting in existing activity. So when back button pressed , then it quite to main activity and application close. I want to do that in such a case "new activity" should be terminate and existing activity must start again. And then if again BACK button pressed then it should terminate main activity.
I override the onKeyDown() down method as follow but it. dose not working properly?
In my new activity.
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK){
childActivity = null;
contentViewLayout.removeAllViews();
mainActivity = new Intent(this,MainActivity.class);
View view = activityManager.startActivity(id, intent).getDecorView();
contentViewLayout.addView(view, contentViewLayoutParams);
return false;
}else{
return super.onKeyDown(keyCode, event);
}
}
But it always quite the application instead of closing child activity
I got it!
Actually the focused activity was the main activity... not the new activity. So all we have to do to set focused to our new activity. So in onCreate() method of new activity I put focused to one any component in new activit e.g..
button.setFocusable(true);
button.requestFocus();
So in such a case new activity onKeyDownButtonWorks
Blockquote
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getKeyCode() == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0 ){
//My code goes here.
return true;
}
return super.onKeyDown(keyCode, event);
}
Take a look at this solution:
ActivityGroup not handling back key for ListActivity

Categories

Resources