יצירת תפריט מגירה מבוסס פרגמנטים


תפריט המבורגר עדכני

שלב ראשון - הפיכת Activity ל- Launcher (לא חובה)

    <activity
        android:name=".activities.MenuActivity"
+        android:exported="true">
+       <intent-filter>
+           <action android:name="android.intent.action.MAIN" />

+           <category android:name="android.intent.category.LAUNCHER" />
+       </intent-filter>
    </activity>
    <activity
        android:name=".activities.MainActivity"
        android:exported="false" />
    
    <activity
        android:name=".activities.MenuActivity"
        android:exported="false" />
    <activity
        android:name=".MainActivity"
        android:exported="true">
-        <intent-filter>
-            <action android:name="android.intent.action.MAIN" />
-            <category android:name="android.intent.category.LAUNCHER" />
-        </intent-filter>
    </activity>
    

הוספת מגירה menu_drawer.xml

יש להוסיף את הקובץ תחת res\menu\ . צריך ליצור את הנתיב הזה באופן הבא:

  1. right click on res that is relatively at the bottom (the one that has layouts)
  2. create new Android Resource Directory, and call it menu
  3. right click this menu folder and select XML and then create xml layout file. call it menu_drawer
  4. copy the content below into the file. You’ll get quite a few error because of non-existing string reference. Add these strings as instructed below.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/nav_main"
        android:title="@string/menu_local_game" />

</menu>

הוספת מחרוזות.

במדריך זה נוספות די הרבה מחרוזות שכדאי שכבר יהיו לכם:

open your res/values/strings.xml and add the missing strings or copy this entirely:

<resources>
    <string name="app_name">TicTacMenu</string>
    <string name="drawer_open">Open navigation drawer</string>
    <string name="drawer_close">Close navigation drawer</string>
    <string name="menu_home">Home</string>
    <string name="menu_local_game">Local Game</string>
    <string name="menu_profile">Profile</string>
    <!-- TODO: Remove or change this placeholder text -->
    <string name="hello_blank_fragment">Hello blank fragment</string>
</resources>

הפיכת MenuActivity ל-drawer

תוספות UI ב- activity_menu.xml:

נשנה בקובץ ה-manifest.xml את האקטיביטי שמבצעת export:

  1. נשנה מ- constraintlayout ל- drawerlayout
  2. נוסיף בתוכו LinearLayout ולתוכו נוסיףcom.google.android.material.navigation.NavigationView:
     <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:orientation="vertical">
    
         <com.google.android.material.appbar.MaterialToolbar
             android:id="@+id/toolbar"
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:background="?attr/colorSurface"
             android:theme="@style/ThemeOverlay.Material3.ActionBar"
             app:title="@string/app_name" />
    
         <FrameLayout
             android:id="@+id/content_container"
             android:layout_width="match_parent"
             android:layout_height="0dp"
             android:layout_weight="1">
    
             <TextView
                 android:id="@+id/menu_hint"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_gravity="center"
                 android:text="@string/menu_hint" />
         </FrameLayout>
     </LinearLayout>
    
     <com.google.android.material.navigation.NavigationView
         android:id="@+id/navigation_view"
         android:layout_width="wrap_content"
         android:layout_height="match_parent"
         android:layout_gravity="start"
         android:fitsSystemWindows="true"
         app:menu="@menu/menu_drawer" />
    

שינוי JAVA

שינוי בקובץ MenuActivity.java

הוספת imports - הרוב יקרה אוטומטית

import android.content.Intent;

import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;

import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.navigation.NavigationView;

הוספת משתנים בתוך מחלקת ה-JAVA

    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle drawerToggle;

עדכון onCreate:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);

        drawerLayout = findViewById(R.id.drawer_layout);
        MaterialToolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        drawerToggle = new ActionBarDrawerToggle(
                this,
                drawerLayout,
                toolbar,
                R.string.drawer_open,
                R.string.drawer_close
        );
        drawerLayout.addDrawerListener(drawerToggle);
        drawerToggle.syncState();

        NavigationView navigationView = findViewById(R.id.navigation_view);
        navigationView.setNavigationItemSelectedListener(item -> {
            if (item.getItemId() == R.id.nav_main) {
                startActivity(new Intent(this, MainActivity.class));
            }
            drawerLayout.closeDrawer(GravityCompat.START);
            return true;
        });
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (drawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
-       EdgeToEdge.enable(this);
        setContentView(R.layout.activity_menu);
-       ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
-           Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
-           v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
-           return insets;
        });
    }
    

Did you add an +id to your main activity?

מדריך זה פונה ל-MainActivity כדי להריץ אותו מתוך ה-menu.

** לכן חשוב להוסיף בקובץ activity_main.xml :**

  • android:id="@+id/main"

וגם ב- activity_menu.xml חשוב שיופיע:

  • android:id="@+id/drawer_layout"

עוד דבר קטן:

בשלב זה נותר רק לחזור לקובץ MenuActivity.Java ולגלות שהנסיון להפעיל Intent (מה שהולך להריץ את MainActivity) עדיין מופיע באדום.

אם תשימו את העכבר על זה תוכלו להוסיף באופן אוטומטי import למחלקה, ואז לא יהיו יותר הערות באדום.