Quiero utilizar el botón back de Android para volver a la página anterior estando en un Fragment. Antes se cerraba la aplicación directamente, pero el código que tengo ahora me parece que tiene que funcionar, pero le falta algo. Este código es de otro post que he encontrado aquí, pero no me vuelve a la página en que estaba yo antes.
Supongo que lo debería hacer en el MainActivity.java, pero cuando meto allí el getActivity().onBackPressed(); me sale que no FragmentManager ya está ejecutando una transacción...
Lo he marcado con un asterisco abajo.
Fragment
public class PostDetailFragment extends Fragment {
private String postid;
private PostAdapter postAdapter;
private List<Post> postList;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_post_detail, container, false);
((DrawerLocker) getActivity()).setDrawerLocked(true);
postList = new ArrayList<>();
postAdapter = new PostAdapter(getContext(), postList);
recyclerView.setAdapter(postAdapter);
readPosts();
return view;
}
@Override
public void onDestroy() {
((DrawerLocker) getActivity()).setDrawerLocked(false);
super.onDestroy();
}
** @Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
return event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK;
}
});
}
}
MainActivity
public class MainActivity extends AppCompatActivity implements DrawerLocker, NavigationView.OnNavigationItemSelectedListener {
ImageView image_profile;
TextView fullname;
private DrawerLayout drawer;
BottomNavigationView bottomNavigationView;
Fragment selectedFragment = null;
FirebaseUser firebaseUser;
String profileid;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
//Dealing with the header
View headerLayout = navigationView.getHeaderView(0);
image_profile = headerLayout.findViewById(R.id.image_profile);
fullname = headerLayout.findViewById(R.id.fullname_header);
SharedPreferences prefs = getApplicationContext().getSharedPreferences("PREFS", Context.MODE_PRIVATE);
profileid = prefs.getString("profileid", "none");
//Called method userInfo() from EditProfile.java here so that header picture changes.
userInfo();
bottomNavigationView = findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(navigationItemSelectedListener);
Bundle intent = getIntent().getExtras();
if (intent != null) {
String publisher = intent.getString("publisherid");
SharedPreferences.Editor editor = getSharedPreferences("PREFS", MODE_PRIVATE).edit();
editor.putString("profileid", publisher);
editor.apply();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ProfileFragment()).commit();
} else {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new HomeFragment()).commit();
}
}
@Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
int id = menuItem.getItemId();
switch (id) {
case R.id.nav_edit_profile:
Intent editProfile = new Intent(MainActivity.this, EditProfileActivity.class);
startActivity(editProfile);
break;
case R.id.nav_settings:
Intent settings = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(settings);
break;
case R.id.nav_logout:
Intent logout = new Intent(MainActivity.this, StartActivity.class);
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(MainActivity.this, StartActivity.class)
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_edit_profile) {
return true;
}
return super.onOptionsItemSelected(item);
}
private BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.nav_home:
selectedFragment = new HomeFragment();
break;
case R.id.nav_search:
selectedFragment = new SearchFragment();
break;
case R.id.nav_notifications:
selectedFragment = new NotificationsFragment();
break;
case R.id.nav_profile:
SharedPreferences.Editor editor = getSharedPreferences("PREFS", MODE_PRIVATE).edit();
editor.putString("profileid", FirebaseAuth.getInstance().getCurrentUser().getUid());
editor.apply();
selectedFragment = new ProfileFragment();
break;
case R.id.nav_save:
selectedFragment = new SaveFragment();
break;
}
if (selectedFragment != null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
selectedFragment).commit();
}
return true;
}
};
public void setDrawerLocked(boolean enabled) {
if (enabled) {
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
} else {
drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}
}
private void userInfo() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser.getUid());
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (getApplicationContext() == null) {
return;
}
User user = dataSnapshot.getValue(User.class);
if (user != null) {
fullname.setText(user.getFullname());
Glide.with(getApplicationContext()).load(user.getImageurl()).into(image_profile);
} else {
return;
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
}