(Using Android Studio 2021.1.1)
Creating a new project using the Navigation Drawer Activity:
- Created a default android application with the Navigation Drawer Activity template.
- Added a Settings Fragment to the project to test the
action_settings
menu and config menu items. - Overridded
onOptionsItemSelected()
inMainActivity.java
to handle the settings menu like so:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Bundle bundle = new Bundle();
switch (item.getItemId()) {
case R.id.action_settings:
Navigation
.findNavController(this, R.id.nav_host_fragment_content_main)
.navigate(R.id.nav_settings);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Testing:
Run the project, the drawer menu works fine and opens fragments as expected. The problem is that when you click on the overflow menu to open the settings fragment it works, but the drawer menu doesn't work anymore when opening the home fragment.
Observation:
After some testing, I found that it's because of the dependency version, downgrading it to 2.3.5 from 2.4.1 resolves the issue.
Is there something wrong with my code or is it because of an API change? How do I handle this without downgrading?
Extra info:
In MainActivity
's onCreate()
method I added the following:
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow, R.id.nav_settings)
.setOpenableLayout(drawer)
.build();
app
module's build.gradle
:
plugins {
id 'com.android.application'
}
android {
compileSdk 31
defaultConfig {
applicationId "com.example.myapplication"
minSdk 23
targetSdk 31
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),
'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildFeatures {
viewBinding true
}
buildToolsVersion '32.0.0'
ndkVersion '23.1.7779620'
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.4.1'
implementation 'com.google.android.material:material:1.5.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.1'
implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.1'
implementation 'androidx.navigation:navigation-fragment:2.4.1'
implementation 'androidx.navigation:navigation-ui:2.4.1'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
}