I am developing an Android Application which contains the Tabs Activity. My Tabs activity contains four tabs(Fragments--[1][2][3][4]). What I want is when I press the Back button it must be redirected to the previous tab, not to the first tab. Like
[4] -> [3]
[3] -> [2]
[2] -> [1]
[1] -> Alert to logout from the App
Please help me out. What do I have to write in my TabsActivity class.
Assumption
Your four fragments is hoted with ViewPager.
Logic
You can write your code into
#Override
void onBackPressed()
{
if(viewPager.getCurrentItem==3)
{
viewPager.setCurrentItem(2)
}
else if{
}
}
and like wise
Use logics instead of hardcoding page numbers.
Below solution works with 2,3,... n, every number of items in Viewpager.
#Override
public void onBackPressed() {
if (viewPager.getCurrentItem() != 0) {
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
} else super.onBackPressed();
}
If you are using TabHost then you can use this solution.
In your attached Activity onBackPressed() you have to implement like below,
#Override
void onBackPressed()
{
if(viewPager.getCurrentItem==3){
viewPager.setCurrentItem(2)
}
else if{
//do your stuff here
}
}
Related
I am trying to collapse bottomSheetBehaviour, bottomSheetVehaviour collapse perfect but after that when I backPress, backpress dosen't work remains in the same activity. Can anyone please give some solution.
#Override
public void onBackPressed() {
if (!mbottomSheetBehavior.isHideable()){
super.onBackPressed();
}else {
mbottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
}
I am writing a code for onBackPressed() method.
Actually, I want that if the user click on back press it check that If the RecyclerView is visible then it should just close the RecyclerView or if it is invisible it should go to another activity.
How I can do it ? Thanks
Simple you can check the visibilty of the recyclerView like
if ( recyclerView.getVisibility() == View.VISIBLE )
and can can decision what you want to do.
For Example: You have to #Override onBackPressed() function to manage your logic like this:
#Override
public void onBackPressed() {
if (recyclerView.getVisibility() == View.VISIBLE) {
//do it here when recyclerview in visible
} else {
//go to any activity or
//simply supper method will take you on previous activity
super.onBackPressed();
}
}
Assume you have done something like recyclerView = findViewById(R.id.something) already.
#Override
public void onBackPressed() {
if (recyclerView.getVisibility() == View.VISIBLE) {
recyclerView.setVisibility(View.INVISIBLE);
} else {
super.onBackPressed();
}
}
As suggested by #bruno above, actually you have the answer in mind already. All you have to do is implement it and see if it works.
Im trying with no success to disable the back key only in one fragment, in the first one.
I did the override of the onBackPressed method on the Activity that contains the fragment with this:
#Override
public void onBackPressed() {
if (this.fragmentManager.getBackStackEntryCount() > 1) {
//getFragmentManager().popBackStack();
super.onBackPressed();
} else {
//super.onBackPressed();
}
}
So, it works perfectly. BUT when i finish all the path of fragments, at the final fragment i have a button that take me back to the first fragment. I will paste the code where i load this fragment again.
for (Fragment fragment1:getSupportFragmentManager().getFragments()) {
getSupportFragmentManager().beginTransaction().remove(fragment1).commit();
}
MontoFragment montoFragment = new MontoFragment();
cargarFragment(montoFragment);
And here the "cargarFragment()" method
public void cargarFragment(Fragment fragment){
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.animation_slide_in,R.anim.animation_slide_out);
fragmentTransaction.replace(R.id.layoutContenedorFragments,fragment);
fragmentTransaction.addToBackStack(null).commit();
}
After i complete all the fragments and i go back to the first one with that, my onBackPressed method doesnt work anymore, because this.fragmentManager.getBackStackEntryCount() > 1 now is 5 or 6 i dont remember now. And this make the back key enable.
So i dont know what to do.
Thanks!
I just achieve it with this code
#Override
public void onBackPressed() {
Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.layoutContenedorFragments);
if (currentFragment instanceof MontoFragment){
}else{
super.onBackPressed();
}
}
i got the current fragment and if this one is an instanceOf That Fragment just do nothing but if not just do the normal onBackPressed.
I look that it works great
try to use popBackStack, replace code block:
for (Fragment fragment1:getSupportFragmentManager().getFragments()) {
getSupportFragmentManager().beginTransaction().remove(fragment1).commit();
}
MontoFragment montoFragment = new MontoFragment();
cargarFragment(montoFragment);
by
void popFragments(int number) {
for (int i = 0, i < number, i++) {
supportFragmentManager.popBackStackImmediate()
}
}
number here is the number of fragments you want to remove, ex: we have fragment 1,2,3,4, so when we are in fragment 4 and want to back to fragment 1, so the number will be 3.
I am simply trying to click back and navigate to my previous activity. My flow is this: I go to news_feed activity -> Comments activity -> User Profile activity -> click back (Go to Comments activity) -> click back (This does nothing for some reason) -> Click back (Go back to news_feed activity). I'm not sure why I have to click back twice when I try to go from Comments activity back to news_feed activity. If I go from news_feed activity -> Comments -> press back (Go to news_feed activity) this works perfectly. Here is my code:
news_feed.java:
#Override
public void onBackPressed() {
super.onBackPressed();
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
Comments.java:
#Override
public void onBackPressed() {
super.onBackPressed();
this.finish();
}
UserProfile.java:
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(UserProfile.this, Comments.class);
Bundle bundle = new Bundle();
bundle.putString("postId", postId);
bundle.putString("posterUserId", posterUserId);
bundle.putString("posterName", posterName);
bundle.putString("postStatus", postStatus);
bundle.putString("postTimeStamp", postTimeStamp);
bundle.putString("postTitle", postTitle);
intent.putExtras(bundle);
startActivity(intent);
finish();
}
I don't think navigating to these activities would change anything, but I can include the intents that I used to navigate to these activities also if necessary. Otherwise I just included the onBackPressed code that I had for these activities. Any ideas why this might cause a problem? Any help would be appreciated. Thanks.
In your UserProfile class, in onBackPressed() method, you are starting the Comments class again. Why do you have to do this?
What is happening is, you are starting a new Comments activity onBackPressed() of the USerProfile class, so there are two instances of Comments Activity. So you feel you are pressing back btn twice.
If you have to pass data back to Comments from UserProfile class, then make use of setResult() method.
This will be of help
How to pass data from 2nd activity to 1st activity when pressed back? - android
Sending data back to the Main Activity in android
I you want to send back the result to previous activity the start activity by using
startActivityForResult()
insead of
startActivity()
and don't override
onBackPressed()
You can try something like this:
private boolean clicked;
#Override
public void onBackPressed() {
if (!clicked) { // if it was not clicked before, change the value of clicked to true and do nothing directly return, if clicked again, then it will be finish the activity.
clicked=true;
return;
}
super.onBackPressed();
}
And if you are going to use the time, then you can do like this:
private long lastClicked;
#Override
public void onBackPressed() {
if (System.currentTimeMillis() - lastClicked < 1000) { // within one second
super.onBackPressed();
}
lastClicked = System.currentTimeMillis();
}
You don't need to override onBackPressed() if all you're going to do is call startActivity() and finish() in the current activity. The Android backstack will handle both of those for you. Moreover, in your UserProfile.java you are passing data to previous activity. For this, you should use startActvityForResult() in the Comments activity (i.e the previous activity) instead of startActivity().
To learn more about startActvityForResult() visit: https://developer.android.com/training/basics/intents/result.html
public void onBackPressed() {
if (this.lastBackPressTime < System.currentTimeMillis() - 2000) {
this.lastBackPressTime = System.currentTimeMillis();
} else {
//super.onBackPressed(); for exit
//INTENT HERE TO YOUR SECOND ACTIVITY like below
Intent intent=new Intent(A.this,B.class);
startActivirty(intent);
}
}
Create a global variable
private long lastBackPressTime = 0;
Hope this will help you,Let me know..
I have main activity and 2 fragments on it, fragment1 call fragment2
When I am clicking the back button from the built in android buttons it call the onBackPressed function that I overrided in the main activity and exit me from the app.
I want that when I click back on the fragment 2 the onBackPressed of the main activity will not called and it will back me to fragment 1.
The back button of the action bar works well (I think it mean that the backstack is ok).
I tried to do:
getActivity().getSupportFragmentManager().beginTransaction().addToBackStack("Messages");
on the fragment 2
And tried to add
getSupportFragmentManager().popBackStack();
to the onBackPressed() of the main activity
It dosen't did nothing
Thank you
EDIT:
I am trying to do
public void onBackPressed() {
// getSupportFragmentManager().popBackStack();
android.support.v4.app.Fragment fragment2 = getSupportFragmentManager().findFragmentByTag(null);
if (fragment2 != null && fragment2.isVisible()) {
getSupportFragmentManager().popBackStack();
return;
}
and before any show
getSupportFragmentManager().beginTransaction().addToBackStack(null).commit();
tr.show(Fragment2);
but got null on the findFragment(null)
EDIT:
I checked getSupportFragmentManager().beginTransaction().mTail.fragment and saw that the value is the Fragment 1 that I want to be showed, but when I do getSupportFragmentManager().popBackStack(); it dosen't nothing.
Override onBackPressed() in Main activity.
Check the currently displayed fragment, if fragment2 is displayed, then pop back stack.
example:
#Override
public void onBackPressed() {
Fragment fragment2 = getFragmentManager().findFragmentByTag("tag");
if (fragment2 != null && fragment2.isVisible()) {
getFragmentManager().popBackStack();
} else {
finish();
}
}
just use below way; in your Activity check this
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Fragment fragment = getSupportFragmentManager().findFragmentByTag("SecondFragment");
if (fragment instanceof SecondFragment) {
// show first fragment
}else{
// finish();
}
}
i have used findFragmentByTag, you can also use findFragmentById
i agree with #Minhtdh comment but it only applicable if you replace one over other
Before calling fragment2.show() in the MainActivity, add the fragmnet transaction to backstack. There is no need to override onBackPressed().By default android implements the same functionality for you.
simple working code.
to get back to 1st fargment.
yourviewvariable.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().onBackPressed();
}
});
Sorry that I miss typed, I mean method onBackPressed.
But for your case, because you use FragmentTransition.show(), it will not add the fragment to backstack and popBackStack won't work. So I think you should try this:
1. don't called getSupportFragmentManager().beginTransaction().addToBackStack(null).commit(); because it add an unnecessary backstack.
2. don't store the "tr" variable as global variable, and you also need call commit() to end the transaction:
Fragment2.setTag("fragment2");
getSupportFragmentManager().beginTransaction().show(Fragment2).commit();
3. in onBackPressed():
android.support.v4.app.Fragment fragment2 = getSupportFragmentManager().findFragmentByTag("fragment2");
if (fragment2 != null && fragment2.isVisible()) {
getSupportFragmentManager().beginTransaction().hide(fragment2).commit();
return;
} else {
super.onBackPressed();
}
Hope this help.