OnBackPressed() is not working in activities - android

In my project, there are three fragments on the dashboard activity ( the default is selected as a home fragment) with a bottom navigation bar. In the Second fragment(connection fragment), there is a recycler view and when the items are clicked, an activity will be open.
The problem is after opening the activity when I click the back button (I have implemented an image button to go back), it goes to the home fragment, not the connections fragment which has the recycler view.Here is the implemented code.
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onKeyUp(int,KeyEvent);
}
});
#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() {
finish();
}
Can someone explain what is the issue.I want to go back to the connection fragment.My bottom navigation bar code as follows,
private BottomNavigationView.OnNavigationItemSelectedListener selectedListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.navigation_discover:
DiscoverFragment fragment1=new DiscoverFragment();
FragmentTransaction ft1=getSupportFragmentManager().beginTransaction();
ft1.replace(R.id.content,fragment1 ,"");
ft1.commit();
return true;
case R.id.navigation_places:
PlacesFragment fragment2=new PlacesFragment();
FragmentTransaction ft2=getSupportFragmentManager().beginTransaction();
ft2.replace(R.id.content,fragment2 ,"");
ft2.commit();
return true;
case R.id.navigation_connections:
ConnectionFragment fragment3=new ConnectionFragment();
FragmentTransaction ft3=getSupportFragmentManager().beginTransaction();
ft3.replace(R.id.content,fragment3 ,"");
ft3.commit();
return true;
case R.id.navigation_profile:
ProfileFragment fragment4=new ProfileFragment();
FragmentTransaction ft4=getSupportFragmentManager().beginTransaction();
ft4.replace(R.id.content,fragment4 ,"");
ft4.commit();
return true;
}
return false;
}
};

Related

(Android) NavigationBarView clear GridView

I have three fragment in NavigationBarView.
First fragment has gridview(gridview data is dynamic by network search).
But when I go to second fragment and back to first fragment, the gridview in first fragment is clear.
How can I prevent the gridview's data from being cleared?
Here my navigation code.
// in global variable
NavigationBarView navigationBarView;
FirstFragment firstFragment;
SecondFragment secondFragment;
ThirdFragment thirdFragment;
// ...
firstFragment = new FirstFragment();
secondFragment= new SecondFragment();
thirdFragment = new ThirdFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.containers, firstFragment).commit();
navigationBarView = findViewById(R.id.bottom_navigationview);
navigationBarView.setKeepScreenOn(true);
navigationBarView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch(item.getItemId())
{
case R.id.menu_first:
getSupportFragmentManager().beginTransaction().replace(R.id.containers, firstFragment).commit();
return true;
case R.id.menu_second:
getSupportFragmentManager().beginTransaction().replace(R.id.containers, secondFragment).commit();
return true;
case R.id.menu_third:
getSupportFragmentManager().beginTransaction().replace(R.id.containers, thirdFragment).commit();
return true;
}
return false;
}
});
addToBackStack method when replacing one fragment by another:
getFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).addToBackStack("my_fragment").commit();
and also use onbackpressed to back with state using back button
#Override
public void onBackPressed() {
if (getParentFragmentManager().getBackStackEntryCount() > 0) {
getParentFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}
use same popBackStack() to navigate from navigationbar also

RecyclerView not displayed after changing fragment

I have the following situation: an activity with three fragments that I switch between them, in the fragment A for example I fetch some data, save it into an array and I set a recycler view using that array. Then I go to some other fragment, B, and when turning back to A the recycler view is not displayed anymore.
How can I solve this situation? I tried to put in the onResume method of the fragment mAdapter.notifyDataSetChanged() but it didn't worked.
How I swap the fragments:
mMainNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.navigation_home:
setFragment(homeFragment);
return true;
case R.id.navigation_search:
setFragment(searchFragment);
return true;
case R.id.navigation_notifications:
setFragment(notificationsFragment);
return true;
}
return false;
}
});
private void setFragment(Fragment fragment) {
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_frame, fragment);
fragmentTransaction.commit();
}

Adding back button to fragment

I have a bottom navigation bar that contains 4 fragments and when a tab is selected a new instance of that fragment is loaded.
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment fragment = null;
switch (item.getItemId()) {
case R.id.navigation_home:
fragment = HomeFragment.newInstance();
break;
case R.id.navigation_cards:
fragment = CardsFragment.newInstance();
break;
case R.id.navigation_deals:
fragment = DealsFragment.newInstance();
break;
case R.id.navigation_settings:
fragment = SettingsFragment.newInstance();
break;
}
if (fragment != null) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.content, fragment);
fragmentTransaction.commit();
}
return true;
}
};
Now in my HomeFragment there is a RecyclerView that On Item Select it opens a new Fragment:
myViewHolder.cardView.setOnClickListener(view -> {
System.out.println("clicked");
Fragment fragment = new TargetDetailsFragment();
FragmentTransaction ft = ((AppCompatActivity) context).getSupportFragmentManager()
.beginTransaction();
ft.replace(R.id.content, fragment).addToBackStack(null);
ft.commit();
});
I want to add a back button to the TargetDetails Fragments that takes you back to the home page when selected and I attempted doing that by implementing OnBackStackChangedListener in the Main activity
#Override
public void onBackStackChanged() {
shouldDisplayHomeUp();
}
public void shouldDisplayHomeUp(){
//Enable Up button only if there are entries in the back stack
boolean canback = getSupportFragmentManager().getBackStackEntryCount()>0;
getSupportActionBar().setDisplayHomeAsUpEnabled(canback);
}
#Override
public boolean onSupportNavigateUp() {
//This method is called when the up button is pressed. Just the pop back stack.
getSupportFragmentManager().popBackStack();
return true;
}
}
but the problem is when I click on it its reloads the HomeFragment Again but I simply want it to go back to the saved instance of that Fragment
Here is my code that I have used for the ViewPager, the idea is to see if the current page number is 0 than to proceed super.onBackPressed(); otherwise go to the previous fragment:
#Override
public void onBackPressed() {
if(vpPager.getCurrentItem()!=0) {
vpPager.setCurrentItem(vpPager.getCurrentItem()-1, true);
} else {
super.onBackPressed();
}
}
By adding below code in your Activity.
The fragment back stack can be managed.
#Override
public void onBackPressed() {
int count = getFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
//additional code
} else {
getFragmentManager().popBackStack();
}
}
Hello #Bolu Okunaiya i think you should try this it will help you to manage backstack to desired fragment without loading same fragment again.
For Stop loading previous fragment you should use "add" instead of "replace" with your FragmentTransaction
Inside your MainActivity
#Override
public void onBackStackChanged() {
//shouldDisplayHomeUp();
Fragment currentFragment = getActivity().getFragmentManager()
.findFragmentById(R.id.fragment_container);
if (currentFragment instanceof TargetDetails) {
Log.v(TAG, "your current fragment is TargetDetails");
popBackStackImmediate(); //<<<< immediate parent fragment will open,which is your HomeFragement
}
}
To use popBackStackImmediate() you need to *replace FragmentA with FragmentB and use addToBackstack() before commit().

Go back to fragment from activity

I have the following Activity code:-
public class legislator_info extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_legislator_info);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Legislator Info");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Intent i = getIntent();
String bioguide = i.getExtras().getString("Person");
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// click on 'up' button in the action bar, handle it here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
So basically I have a fragment which has a list view displayed in it. On click of a list Item I start this activity and I want to go back to the previous fragment on the back button click. I tried the above code but I am not able to travel back. Am pretty new at this any help is appreciated.
I have added my fragment in the following way:-
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
LegislatorFragment lf = new LegislatorFragment();
ft.replace(R.id.fragment_container,lf);
ft.addToBackStack(null);
ft.commit();
I am still not clear what you want to achieve but you can try this
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
EDIT:
case android.R.id.home:
//call onBackPressed here
onBackPressed();
return true;
You have to override onOptionsItemSelected because you are trying with Action bar's back button.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
Then override BackPressed -
#Override
public void onBackPressed()
{
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
}
else {
super.onBackPressed();
}
}

Toolbar back button does not close current Fragment

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

Categories

Resources