close drawer on back press

This commit is contained in:
Daniel Gultsch 2023-02-28 06:41:33 +01:00
parent 6ef2997b5e
commit c3f5273813
No known key found for this signature in database
GPG key ID: F43D18AD2A0982C2

View file

@ -7,9 +7,11 @@ import android.view.Menu;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil; import androidx.databinding.DataBindingUtil;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider; import androidx.lifecycle.ViewModelProvider;
import com.google.android.material.elevation.SurfaceColors; import com.google.android.material.elevation.SurfaceColors;
@ -71,9 +73,37 @@ public class OverviewFragment extends Fragment {
this.overviewViewModel this.overviewViewModel
.getChatFilterAvailable() .getChatFilterAvailable()
.observe(getViewLifecycleOwner(), this::onChatFilterAvailable); .observe(getViewLifecycleOwner(), this::onChatFilterAvailable);
this.configureDrawerLayoutToCloseOnBackPress();
return binding.getRoot(); return binding.getRoot();
} }
private void configureDrawerLayoutToCloseOnBackPress() {
final OnBackPressedCallback onBackPressedCallback =
new OnBackPressedCallback(false) {
@Override
public void handleOnBackPressed() {
binding.drawerLayout.close();
}
};
this.binding.drawerLayout.addDrawerListener(
new DrawerLayout.SimpleDrawerListener() {
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
onBackPressedCallback.setEnabled(true);
}
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
onBackPressedCallback.setEnabled(false);
}
});
requireActivity()
.getOnBackPressedDispatcher()
.addCallback(getViewLifecycleOwner(), onBackPressedCallback);
}
private boolean onNavigationItemSelected(final MenuItem menuItem) { private boolean onNavigationItemSelected(final MenuItem menuItem) {
if (menuItem.getItemId() == R.id.chats) { if (menuItem.getItemId() == R.id.chats) {
setChatFilter(null); setChatFilter(null);