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

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

How to create side navigation bar in Android

问题

  1. 我正试图在我的应用程序中创建侧边导航栏我的MainActivity代码如下
  2. package com.thechamp.ait;
  3. import androidx.annotation.NonNull;
  4. import androidx.annotation.RequiresApi;
  5. import androidx.appcompat.app.ActionBar;
  6. import androidx.appcompat.app.ActionBarDrawerToggle;
  7. import androidx.appcompat.app.AppCompatActivity;
  8. import android.os.Build;
  9. import android.os.Bundle;
  10. import android.view.Menu;
  11. import android.view.MenuItem;
  12. import android.view.accessibility.AccessibilityRecord;
  13. import android.widget.Toast;
  14. import androidx.appcompat.widget.Toolbar;
  15. import androidx.core.view.GravityCompat;
  16. import androidx.drawerlayout.widget.DrawerLayout;
  17. import com.google.android.material.navigation.NavigationView;
  18. import java.security.MessageDigest;
  19. import java.util.Calendar;
  20. public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
  21. private DrawerLayout drawerLayout;
  22. private NavigationView navigationView;
  23. @Override
  24. protected void onCreate(Bundle savedInstanceState) {
  25. super.onCreate(savedInstanceState);
  26. setContentView(R.layout.activity_main);
  27. Toolbar toolbar = findViewById(R.id.toolbar);
  28. setSupportActionBar(toolbar);
  29. getSupportActionBar().setTitle(null);
  30. navigationView = findViewById(R.id.nav_view);
  31. navigationView.setItemIconTintList(null);
  32. Calendar c = Calendar.getInstance();
  33. int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
  34. if (timeOfDay >= 0 && timeOfDay < 12) {
  35. Toast.makeText(this, "Good Morning", Toast.LENGTH_SHORT).show();
  36. } else if (timeOfDay >= 12 && timeOfDay < 16) {
  37. Toast.makeText(this, "Good Afternoon", Toast.LENGTH_SHORT).show();
  38. } else if (timeOfDay >= 16 && timeOfDay < 21) {
  39. Toast.makeText(this, "Good Evening", Toast.LENGTH_SHORT).show();
  40. } else if (timeOfDay >= 21 && timeOfDay < 24) {
  41. Toast.makeText(this, "Good Night", Toast.LENGTH_SHORT).show();
  42. }
  43. drawerLayout = findViewById(R.id.drawer_layout);
  44. navigationView.setNavigationItemSelectedListener(this);
  45. ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
  46. drawerLayout.addDrawerListener(toggle);
  47. toggle.syncState();
  48. }
  49. @Override
  50. public boolean onNavigationItemSelected(MenuItem item) {
  51. switch (item.getItemId()) {
  52. case R.id.nav_about:
  53. getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new AboutCollege()).commit();
  54. break;
  55. case R.id.nav_Earnmoney:
  56. getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new EarnMoney()).commit();
  57. break;
  58. case R.id.nav_Feedback:
  59. getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Feedback()).commit();
  60. break;
  61. case R.id.nav_notice:
  62. getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new NoticeBoard()).commit();
  63. break;
  64. case R.id.nav_study:
  65. getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new StudyMaterial()).commit();
  66. break;
  67. case R.id.nav_support:
  68. getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Support()).commit();
  69. break;
  70. }
  71. drawerLayout.closeDrawer(GravityCompat.START);
  72. return true;
  73. }
  74. @Override
  75. public void onBackPressed() {
  76. if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
  77. drawerLayout.closeDrawer(GravityCompat.START);
  78. } else {
  79. super.onBackPressed();
  80. }
  81. }
  82. }

以下是activitymain.xml的内容:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:id="@+id/drawer_layout"
  6. android:layout_width="match_parent"
  7. android:layout_height="match_parent"
  8. android:fitsSystemWindows="true"
  9. tools:context=".MainActivity"
  10. tools:openDrawer="start">
  11. <LinearLayout
  12. android:layout_width="match_parent"
  13. android:layout_height="match_parent"
  14. android:orientation="vertical" />
  15. <androidx.appcompat.widget.Toolbar
  16. android:id="@+id/toolbar"
  17. android:layout_width="match_parent"
  18. android:layout_height="?attr/actionBarSize"
  19. android:background="@drawable/background_pic"
  20. android:elevation="4dp"
  21. android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
  22. app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
  23. <FrameLayout
  24. android:id="@+id/fragment_container"
  25. android:layout_width="match_parent"
  26. android:layout_height="match_parent" />
  27. <com.google.android.material.navigation.NavigationView
  28. android:id="@+id/nav_view"
  29. android:layout_width="wrap_content"
  30. android:layout_height="match_parent"
  31. android:layout_gravity="start"
  32. app:headerLayout="@layout/nav_header"
  33. app:itemIconTint="@null"
  34. app:menu="@menu/drawer_menu" />
  35. </androidx.drawerlayout.widget.DrawerLayout>

你创建了一个侧边导航栏的代码,但点击特定的导航项后无法打开片段。你能分享一下你的错误日志吗?

  1. <details>
  2. <summary>英文:</summary>
  3. I am trying to create side navigation bar in my app. My mainactivity code is:
  4. package com.thechamp.ait;
  5. import androidx.annotation.NonNull;
  6. import androidx.annotation.RequiresApi;
  7. import androidx.appcompat.app.ActionBar;
  8. import androidx.appcompat.app.ActionBarDrawerToggle;
  9. import androidx.appcompat.app.AppCompatActivity;
  10. import android.os.Build;
  11. import android.os.Bundle;
  12. import android.view.Menu;
  13. import android.view.MenuItem;
  14. import android.view.accessibility.AccessibilityRecord;
  15. import android.widget.Toast;
  16. import androidx.appcompat.widget.Toolbar;
  17. import androidx.core.view.GravityCompat;
  18. import androidx.drawerlayout.widget.DrawerLayout;
  19. import com.google.android.material.navigation.NavigationView;
  20. import java.security.MessageDigest;
  21. import java.util.Calendar;
  22. public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
  23. private DrawerLayout drawerLayout;
  24. private NavigationView navigationView;
  25. @Override
  26. protected void onCreate(Bundle savedInstanceState) {
  27. super.onCreate(savedInstanceState);
  28. setContentView(R.layout.activity_main);
  29. Toolbar toolbar = findViewById(R.id.toolbar);
  30. setSupportActionBar(toolbar);
  31. getSupportActionBar().setTitle(null);
  32. navigationView = findViewById(R.id.nav_view);
  33. navigationView.setItemIconTintList(null);
  34. Calendar c = Calendar.getInstance();
  35. int timeOfDay = c.get(Calendar.HOUR_OF_DAY);
  36. if(timeOfDay &gt;= 0 &amp;&amp; timeOfDay &lt; 12){
  37. Toast.makeText(this, &quot;Good Morning&quot;, Toast.LENGTH_SHORT).show();
  38. }else if(timeOfDay &gt;= 12 &amp;&amp; timeOfDay &lt; 16){
  39. Toast.makeText(this, &quot;Good Afternoon&quot;, Toast.LENGTH_SHORT).show();
  40. }else if(timeOfDay &gt;= 16 &amp;&amp; timeOfDay &lt; 21){
  41. Toast.makeText(this, &quot;Good Evening&quot;, Toast.LENGTH_SHORT).show();
  42. }else if(timeOfDay &gt;= 21 &amp;&amp; timeOfDay &lt; 24){
  43. Toast.makeText(this, &quot;Good Night&quot;, Toast.LENGTH_SHORT).show();
  44. }
  45. drawerLayout = findViewById(R.id.drawer_layout);
  46. navigationView.setNavigationItemSelectedListener(this);
  47. ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
  48. drawerLayout.addDrawerListener(toggle);
  49. toggle.syncState();
  50. }
  51. @Override
  52. public boolean onNavigationItemSelected( MenuItem item) {
  53. switch (item.getItemId()) {
  54. case R.id.nav_about:
  55. getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new AboutCollege()).commit();
  56. break;
  57. case R.id.nav_Earnmoney:
  58. getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new EarnMoney()).commit();
  59. break;
  60. case R.id.nav_Feedback:
  61. getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Feedback()).commit();
  62. break;
  63. case R.id.nav_notice:
  64. getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new NoticeBoard()).commit();
  65. break;
  66. case R.id.nav_study:
  67. getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new StudyMaterial()).commit();
  68. break;
  69. case R.id.nav_support:
  70. getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new Support()).commit();
  71. break;
  72. }
  73. drawerLayout.closeDrawer(GravityCompat.START);
  74. return true;
  75. }
  76. @Override
  77. public void onBackPressed() {
  78. if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
  79. drawerLayout.closeDrawer(GravityCompat.START);
  80. }
  81. else {
  82. super.onBackPressed();
  83. }
  84. }}
  85. And here activitymain.xml
  86. &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
  87. &lt;androidx.drawerlayout.widget.DrawerLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
  88. xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
  89. xmlns:tools=&quot;http://schemas.android.com/tools&quot;
  90. android:id=&quot;@+id/drawer_layout&quot;
  91. android:layout_width=&quot;match_parent&quot;
  92. android:layout_height=&quot;match_parent&quot;
  93. android:fitsSystemWindows=&quot;true&quot;
  94. tools:context=&quot;.MainActivity&quot;
  95. tools:openDrawer=&quot;start&quot;&gt;
  96. &lt;LinearLayout
  97. android:layout_width=&quot;match_parent&quot;
  98. android:layout_height=&quot;match_parent&quot;
  99. android:orientation=&quot;vertical&quot; /&gt;
  100. &lt;androidx.appcompat.widget.Toolbar
  101. android:id=&quot;@+id/toolbar&quot;
  102. android:layout_width=&quot;match_parent&quot;
  103. android:layout_height=&quot;?attr/actionBarSize&quot;
  104. android:background=&quot;@drawable/background_pic&quot;
  105. android:elevation=&quot;4dp&quot;
  106. android:theme=&quot;@style/ThemeOverlay.AppCompat.Dark.ActionBar&quot;
  107. app:popupTheme=&quot;@style/ThemeOverlay.AppCompat.Light&quot; /&gt;
  108. &lt;FrameLayout
  109. android:id=&quot;@+id/fragment_container&quot;
  110. android:layout_width=&quot;match_parent&quot;
  111. android:layout_height=&quot;match_parent&quot; /&gt;
  112. &lt;com.google.android.material.navigation.NavigationView
  113. android:id=&quot;@+id/nav_view&quot;
  114. android:layout_width=&quot;wrap_content&quot;
  115. android:layout_height=&quot;match_parent&quot;
  116. android:layout_gravity=&quot;start&quot;
  117. app:headerLayout=&quot;@layout/nav_header&quot;
  118. app:itemIconTint=&quot;@null&quot;
  119. app:menu=&quot;@menu/drawer_menu&quot; /&gt;
  120. &lt;/androidx.drawerlayout.widget.DrawerLayout&gt;
  121. 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.
  122. Here is my error log:
  123. 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
  124. 2020-10-14 18:11:26.782 363-363/? E/wifi_forwarder: RemoteConnection failed to initialize: RemoteConnection failed to open pipe
  125. 2020-10-14 18:11:39.348 16712-16712/? E/oid.apps.photo: Not starting debugger since process cannot load the jdwp agent.
  126. 2020-10-14 18:11:39.358 16723-16723/? E/android.youtub: Not starting debugger since process cannot load the jdwp agent.
  127. 2020-10-14 18:11:39.427 16723-16723/? E/YouTube: flushBinderConnectionCallbacks is unverified on SDK 30
  128. 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
  129. 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
  130. 2020-10-14 18:11:39.447 506-523/? E/JobScheduler.Background: App com.google.android.gms became active but still in NEVER bucket
  131. 2020-10-14 18:11:39.518 408-425/? E/installd: Couldn&#39;t opendir /data/app/vmdl1992756199.tmp: No such file or directory
  132. 2020-10-14 18:11:39.518 408-425/? E/installd: Failed to delete /data/app/vmdl1992756199.tmp: No such file or directory
  133. 2020-10-14 18:11:39.704 1003-1793/? E/ActivityThread: Failed to find provider info for com.google.android.apps.wellbeing.api
  134. 2020-10-14 18:11:39.896 16723-16788/? E/GEL_DELAYED_EVENT_DEBUG: Failed delayed event dispatch, no dispatchers.
  135. 2020-10-14 18:11:44.711 1003-1793/? E/ActivityThread: Failed to find provider info for com.google.android.apps.wellbeing.api
  136. 2020-10-14 18:11:59.668 506-523/? E/JobScheduler.Background: App com.google.android.gms became active but still in NEVER bucket
  137. 2020-10-14 18:11:59.673 10616-15676/? E/WakeLock: GCM_HB_ALARM release without a matched acquire!
  138. 2020-10-14 18:11:59.727 1003-1793/? E/ActivityThread: Failed to find provider info for com.google.android.apps.wellbeing.api
  139. 2020-10-14 18:12:09.692 506-523/? E/JobScheduler.Background: App com.google.android.gms became active but still in NEVER bucket
  140. 2020-10-14 18:12:09.693 506-523/? E/JobScheduler.Background: App com.google.android.gms became active but still in NEVER bucket
  141. 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
  142. 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
  143. 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
  144. 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
  145. 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
  146. 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
  147. 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
  148. 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
  149. 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
  150. </details>
  151. # 答案1
  152. **得分**: 1
  153. 你没有关闭你的内容框架 `LinearLayout`
  154. ```xml
  155. <?xml version="1.0" encoding="utf-8"?>
  156. <androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
  157. xmlns:app="http://schemas.android.com/apk/res-auto"
  158. xmlns:tools="http://schemas.android.com/tools"
  159. android:id="@+id/drawer_layout"
  160. android:layout_width="match_parent"
  161. android:layout_height="match_parent"
  162. android:fitsSystemWindows="true"
  163. tools:context=".MainActivity"
  164. tools:openDrawer="start">
  165. <!-- this is your content frame - first child of DrawerLayout -->
  166. <LinearLayout
  167. android:layout_width="match_parent"
  168. android:layout_height="match_parent"
  169. android:orientation="vertical">
  170. <androidx.appcompat.widget.Toolbar
  171. android:id="@+id/toolbar"
  172. android:layout_width="match_parent"
  173. android:layout_height="?attr/actionBarSize"
  174. android:background="@drawable/background_pic"
  175. android:elevation="4dp"
  176. android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
  177. app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
  178. <FrameLayout
  179. android:id="@+id/fragment_container"
  180. android:layout_width="match_parent"
  181. android:layout_height="match_parent" />
  182. </LinearLayout>
  183. <!-- ends in here -->
  184. <!-- this is your side bar attached to "start" (layout_gravity param) -->
  185. <com.google.android.material.navigation.NavigationView
  186. android:id="@+id/nav_view"
  187. android:layout_width="wrap_content"
  188. android:layout_height="match_parent"
  189. android:layout_gravity="start"
  190. app:headerLayout="@layout/nav_header"
  191. app:itemIconTint="@null"
  192. app:menu="@menu/drawer_menu" />
  193. <!-- you may add more side bars with different layout_gravity -->
  194. </androidx.drawerlayout.widget.DrawerLayout>
英文:

you are not closing your content frame LinearLayout

  1. &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
  2. &lt;androidx.drawerlayout.widget.DrawerLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
  3. xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
  4. xmlns:tools=&quot;http://schemas.android.com/tools&quot;
  5. android:id=&quot;@+id/drawer_layout&quot;
  6. android:layout_width=&quot;match_parent&quot;
  7. android:layout_height=&quot;match_parent&quot;
  8. android:fitsSystemWindows=&quot;true&quot;
  9. tools:context=&quot;.MainActivity&quot;
  10. tools:openDrawer=&quot;start&quot;&gt;
  11. &lt;!-- this is your content frame - first child of DrawerLayout --&gt;
  12. &lt;LinearLayout
  13. android:layout_width=&quot;match_parent&quot;
  14. android:layout_height=&quot;match_parent&quot;
  15. android:orientation=&quot;vertical&quot;&gt;
  16. &lt;androidx.appcompat.widget.Toolbar
  17. android:id=&quot;@+id/toolbar&quot;
  18. android:layout_width=&quot;match_parent&quot;
  19. android:layout_height=&quot;?attr/actionBarSize&quot;
  20. android:background=&quot;@drawable/background_pic&quot;
  21. android:elevation=&quot;4dp&quot;
  22. android:theme=&quot;@style/ThemeOverlay.AppCompat.Dark.ActionBar&quot;
  23. app:popupTheme=&quot;@style/ThemeOverlay.AppCompat.Light&quot; /&gt;
  24. &lt;FrameLayout
  25. android:id=&quot;@+id/fragment_container&quot;
  26. android:layout_width=&quot;match_parent&quot;
  27. android:layout_height=&quot;match_parent&quot; /&gt;
  28. &lt;/LinearLayout&gt;
  29. &lt;!-- ends in here --&gt;
  30. &lt;!-- this is your side bar attached to &quot;start&quot; (layout_gravity param) --&gt;
  31. &lt;com.google.android.material.navigation.NavigationView
  32. android:id=&quot;@+id/nav_view&quot;
  33. android:layout_width=&quot;wrap_content&quot;
  34. android:layout_height=&quot;match_parent&quot;
  35. android:layout_gravity=&quot;start&quot;
  36. app:headerLayout=&quot;@layout/nav_header&quot;
  37. app:itemIconTint=&quot;@null&quot;
  38. app:menu=&quot;@menu/drawer_menu&quot; /&gt;
  39. &lt;!-- you may add more side bars with different layout_gravity --&gt;
  40. &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:

确定