如何在Android中创建侧边导航栏

huangapple go评论71阅读模式
英文:

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 &gt;= 0 &amp;&amp; timeOfDay &lt; 12){
Toast.makeText(this, &quot;Good Morning&quot;, Toast.LENGTH_SHORT).show();
}else if(timeOfDay &gt;= 12 &amp;&amp; timeOfDay &lt; 16){
Toast.makeText(this, &quot;Good Afternoon&quot;, Toast.LENGTH_SHORT).show();
}else if(timeOfDay &gt;= 16 &amp;&amp; timeOfDay &lt; 21){
Toast.makeText(this, &quot;Good Evening&quot;, Toast.LENGTH_SHORT).show();
}else if(timeOfDay &gt;= 21 &amp;&amp; timeOfDay &lt; 24){
Toast.makeText(this, &quot;Good Night&quot;, 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
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;androidx.drawerlayout.widget.DrawerLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
xmlns:tools=&quot;http://schemas.android.com/tools&quot;
android:id=&quot;@+id/drawer_layout&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot;
android:fitsSystemWindows=&quot;true&quot;
tools:context=&quot;.MainActivity&quot;
tools:openDrawer=&quot;start&quot;&gt;
&lt;LinearLayout
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot;
android:orientation=&quot;vertical&quot; /&gt;
&lt;androidx.appcompat.widget.Toolbar
android:id=&quot;@+id/toolbar&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;?attr/actionBarSize&quot;
android:background=&quot;@drawable/background_pic&quot;
android:elevation=&quot;4dp&quot;
android:theme=&quot;@style/ThemeOverlay.AppCompat.Dark.ActionBar&quot;
app:popupTheme=&quot;@style/ThemeOverlay.AppCompat.Light&quot; /&gt;
&lt;FrameLayout
android:id=&quot;@+id/fragment_container&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot; /&gt;
&lt;com.google.android.material.navigation.NavigationView
android:id=&quot;@+id/nav_view&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;match_parent&quot;
android:layout_gravity=&quot;start&quot;
app:headerLayout=&quot;@layout/nav_header&quot;
app:itemIconTint=&quot;@null&quot;
app:menu=&quot;@menu/drawer_menu&quot; /&gt;
&lt;/androidx.drawerlayout.widget.DrawerLayout&gt;
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&#39;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 &#39;pipe:qemud:wififorward&#39; 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&#39;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

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;androidx.drawerlayout.widget.DrawerLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
xmlns:tools=&quot;http://schemas.android.com/tools&quot;
android:id=&quot;@+id/drawer_layout&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot;
android:fitsSystemWindows=&quot;true&quot;
tools:context=&quot;.MainActivity&quot;
tools:openDrawer=&quot;start&quot;&gt;
&lt;!-- this is your content frame - first child of DrawerLayout --&gt;
&lt;LinearLayout
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot;
android:orientation=&quot;vertical&quot;&gt;
&lt;androidx.appcompat.widget.Toolbar
android:id=&quot;@+id/toolbar&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;?attr/actionBarSize&quot;
android:background=&quot;@drawable/background_pic&quot;
android:elevation=&quot;4dp&quot;
android:theme=&quot;@style/ThemeOverlay.AppCompat.Dark.ActionBar&quot;
app:popupTheme=&quot;@style/ThemeOverlay.AppCompat.Light&quot; /&gt;
&lt;FrameLayout
android:id=&quot;@+id/fragment_container&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot; /&gt;
&lt;/LinearLayout&gt;
&lt;!-- ends in here --&gt;
&lt;!-- this is your side bar attached to &quot;start&quot; (layout_gravity param) --&gt;
&lt;com.google.android.material.navigation.NavigationView
android:id=&quot;@+id/nav_view&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;match_parent&quot;
android:layout_gravity=&quot;start&quot;
app:headerLayout=&quot;@layout/nav_header&quot;
app:itemIconTint=&quot;@null&quot;
app:menu=&quot;@menu/drawer_menu&quot; /&gt;
&lt;!-- you may add more side bars with different layout_gravity --&gt;
&lt;/androidx.drawerlayout.widget.DrawerLayout&gt;

huangapple
  • 本文由 发表于 2020年10月14日 19:22:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/64352175.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定