英文:
How to create side navigation bar in Android
问题
我正试图在我的应用程序中创建侧边导航栏。我的MainActivity代码如下:
package com.thechamp.ait;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.accessibility.AccessibilityRecord;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import com.google.android.material.navigation.NavigationView;
import java.security.MessageDigest;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawerLayout;
private NavigationView navigationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
navigationView = findViewById(R.id.nav_view);
navigationView.setItemIconTintList(null);
Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
if (timeOfDay >= 0 && timeOfDay < 12) {
Toast.makeText(this, "Good Morning", Toast.LENGTH_SHORT).show();
} else if (timeOfDay >= 12 && timeOfDay < 16) {
Toast.makeText(this, "Good Afternoon", Toast.LENGTH_SHORT).show();
} else if (timeOfDay >= 16 && timeOfDay < 21) {
Toast.makeText(this, "Good Evening", Toast.LENGTH_SHORT).show();
} else if (timeOfDay >= 21 && timeOfDay < 24) {
Toast.makeText(this, "Good Night", Toast.LENGTH_SHORT).show();
}
drawerLayout = findViewById(R.id.drawer_layout);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
}
@Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_about:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new AboutCollege()).commit();
break;
case R.id.nav_Earnmoney:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new EarnMoney()).commit();
break;
case R.id.nav_Feedback:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Feedback()).commit();
break;
case R.id.nav_notice:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new NoticeBoard()).commit();
break;
case R.id.nav_study:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new StudyMaterial()).commit();
break;
case R.id.nav_support:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Support()).commit();
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
以下是activitymain.xml的内容:
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" />
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@drawable/background_pic"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/nav_header"
app:itemIconTint="@null"
app:menu="@menu/drawer_menu" />
</androidx.drawerlayout.widget.DrawerLayout>
你创建了一个侧边导航栏的代码,但点击特定的导航项后无法打开片段。你能分享一下你的错误日志吗?
<details>
<summary>英文:</summary>
I am trying to create side navigation bar in my app. My mainactivity code is:
package com.thechamp.ait;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.accessibility.AccessibilityRecord;
import android.widget.Toast;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import com.google.android.material.navigation.NavigationView;
import java.security.MessageDigest;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawerLayout;
private NavigationView navigationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(null);
navigationView = findViewById(R.id.nav_view);
navigationView.setItemIconTintList(null);
Calendar c = Calendar.getInstance();
int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
if(timeOfDay >= 0 && timeOfDay < 12){
Toast.makeText(this, "Good Morning", Toast.LENGTH_SHORT).show();
}else if(timeOfDay >= 12 && timeOfDay < 16){
Toast.makeText(this, "Good Afternoon", Toast.LENGTH_SHORT).show();
}else if(timeOfDay >= 16 && timeOfDay < 21){
Toast.makeText(this, "Good Evening", Toast.LENGTH_SHORT).show();
}else if(timeOfDay >= 21 && timeOfDay < 24){
Toast.makeText(this, "Good Night", Toast.LENGTH_SHORT).show();
}
drawerLayout = findViewById(R.id.drawer_layout);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
}
@Override
public boolean onNavigationItemSelected( MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_about:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new AboutCollege()).commit();
break;
case R.id.nav_Earnmoney:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new EarnMoney()).commit();
break;
case R.id.nav_Feedback:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Feedback()).commit();
break;
case R.id.nav_notice:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new NoticeBoard()).commit();
break;
case R.id.nav_study:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new StudyMaterial()).commit();
break;
case R.id.nav_support:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Support()).commit();
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}}
And here activitymain.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" />
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@drawable/background_pic"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/nav_header"
app:itemIconTint="@null"
app:menu="@menu/drawer_menu" />
</androidx.drawerlayout.widget.DrawerLayout>
I created an side navigation bar with these codes, but I am not able to open fragment after clicking on specific fragment. How can I correct my code. I have follow youtube video but it's not working in my case.
Here is my error log:
2020-10-14 18:11:26.782 363-363/? E/wifi_forwarder: qemu_pipe_open_ns:62: Could not connect to the 'pipe:qemud:wififorward' service: Invalid argument
2020-10-14 18:11:26.782 363-363/? E/wifi_forwarder: RemoteConnection failed to initialize: RemoteConnection failed to open pipe
2020-10-14 18:11:39.348 16712-16712/? E/oid.apps.photo: Not starting debugger since process cannot load the jdwp agent.
2020-10-14 18:11:39.358 16723-16723/? E/android.youtub: Not starting debugger since process cannot load the jdwp agent.
2020-10-14 18:11:39.427 16723-16723/? E/YouTube: flushBinderConnectionCallbacks is unverified on SDK 30
2020-10-14 18:11:39.437 191-197/? E/android.system.suspend@1.0-service: Error opening kernel wakelock stats for: wakeup34: Permission denied
2020-10-14 18:11:39.439 191-197/? E/android.system.suspend@1.0-service: Error opening kernel wakelock stats for: wakeup35: Permission denied
2020-10-14 18:11:39.447 506-523/? E/JobScheduler.Background: App com.google.android.gms became active but still in NEVER bucket
2020-10-14 18:11:39.518 408-425/? E/installd: Couldn't opendir /data/app/vmdl1992756199.tmp: No such file or directory
2020-10-14 18:11:39.518 408-425/? E/installd: Failed to delete /data/app/vmdl1992756199.tmp: No such file or directory
2020-10-14 18:11:39.704 1003-1793/? E/ActivityThread: Failed to find provider info for com.google.android.apps.wellbeing.api
2020-10-14 18:11:39.896 16723-16788/? E/GEL_DELAYED_EVENT_DEBUG: Failed delayed event dispatch, no dispatchers.
2020-10-14 18:11:44.711 1003-1793/? E/ActivityThread: Failed to find provider info for com.google.android.apps.wellbeing.api
2020-10-14 18:11:59.668 506-523/? E/JobScheduler.Background: App com.google.android.gms became active but still in NEVER bucket
2020-10-14 18:11:59.673 10616-15676/? E/WakeLock: GCM_HB_ALARM release without a matched acquire!
2020-10-14 18:11:59.727 1003-1793/? E/ActivityThread: Failed to find provider info for com.google.android.apps.wellbeing.api
2020-10-14 18:12:09.692 506-523/? E/JobScheduler.Background: App com.google.android.gms became active but still in NEVER bucket
2020-10-14 18:12:09.693 506-523/? E/JobScheduler.Background: App com.google.android.gms became active but still in NEVER bucket
2020-10-14 18:12:12.577 506-650/? E/ClipboardService: Denying clipboard access to com.google.android.gms, application is not in focus nor is it a system service for user 0
2020-10-14 18:12:12.577 506-650/? E/ClipboardService: Denying clipboard access to com.android.chrome, application is not in focus nor is it a system service for user 0
2020-10-14 18:12:12.577 506-650/? E/ClipboardService: Denying clipboard access to com.google.android.gms, application is not in focus nor is it a system service for user 0
2020-10-14 18:12:12.826 506-650/? E/ClipboardService: Denying clipboard access to com.google.android.gms, application is not in focus nor is it a system service for user 0
2020-10-14 18:12:12.826 506-650/? E/ClipboardService: Denying clipboard access to com.android.chrome, application is not in focus nor is it a system service for user 0
2020-10-14 18:12:12.826 506-650/? E/ClipboardService: Denying clipboard access to com.google.android.gms, application is not in focus nor is it a system service for user 0
2020-10-14 18:12:13.001 506-650/? E/ClipboardService: Denying clipboard access to com.google.android.gms, application is not in focus nor is it a system service for user 0
2020-10-14 18:12:13.001 506-650/? E/ClipboardService: Denying clipboard access to com.android.chrome, application is not in focus nor is it a system service for user 0
2020-10-14 18:12:13.001 506-650/? E/ClipboardService: Denying clipboard access to com.google.android.gms, application is not in focus nor is it a system service for user 0
</details>
# 答案1
**得分**: 1
你没有关闭你的内容框架 `LinearLayout`
```xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
tools:openDrawer="start">
<!-- this is your content frame - first child of DrawerLayout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@drawable/background_pic"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!-- ends in here -->
<!-- this is your side bar attached to "start" (layout_gravity param) -->
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/nav_header"
app:itemIconTint="@null"
app:menu="@menu/drawer_menu" />
<!-- you may add more side bars with different layout_gravity -->
</androidx.drawerlayout.widget.DrawerLayout>
英文:
you are not closing your content frame LinearLayout
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
tools:openDrawer="start">
<!-- this is your content frame - first child of DrawerLayout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@drawable/background_pic"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<!-- ends in here -->
<!-- this is your side bar attached to "start" (layout_gravity param) -->
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="@layout/nav_header"
app:itemIconTint="@null"
app:menu="@menu/drawer_menu" />
<!-- you may add more side bars with different layout_gravity -->
</androidx.drawerlayout.widget.DrawerLayout>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论