首页 > 解决方案 > 如何使用自定义菜单项创建自定义导航视图

问题描述

我想创建一个具有完全自定义标题视图和菜单项的导航视图(4 个菜单项应该在水平视图中作为网格)。经过一番研究,我设法创建了抽屉布局。但我已经尝试了很多,但未能将菜单项与相关片段链接起来。不知道我在哪里做错了,非常感谢您对此事的任何帮助。请在此处找到我当前的代码。我已经评论了一些我已经尝试过的方法

MainActivity.java

import android.os.Bundle;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.navigation.NavController;
import androidx.navigation.NavOptions;
import androidx.navigation.Navigation;
import androidx.navigation.ui.NavigationUI;


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


public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private DrawerLayout drawerLayout;
    private NavigationView navigationView;
    private Toolbar toolbar;
    public NavController navController;


    @Override
    protected void onCreate(Bundle savedInstanceState) {



        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        drawerLayout = findViewById(R.id.drawer_layout);
        navigationView = findViewById(R.id.navigationView);

        Toolbar toolBar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolBar);
        ActionBar actionBar = getSupportActionBar();
        init();





    }

    private void init(){
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout);
        NavigationUI.setupWithNavController(navigationView, navController);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        menuItem.setChecked(true);
        int id = menuItem.getItemId();
        switch (id) {

           case R.id.profile: {

               NavOptions navOptions = new NavOptions.Builder()
                       .setPopUpTo(R.id.navigation_graph, true)
                       .build();
              Navigation.findNavController(this,R.id.nav_host_fragment).navigate(R.id.profileFragment,null,navOptions);
              //  navController.navigate(R.id.profileFragment);
                break;
            }


/*
            case R.id.profile: {
                Navigation.findNavController(this,R.id.nav_host_fragment).navigate(R.id.profile_settings_fragment);
        }
         */
                //navController.navigate(R.id.profile_settings_fragment);
              // break;

            case R.id.list:{
                navController.navigate(R.id.listFragment);
                break;
  /*
            case R.id.list_of_sessions:

                break;
*/          }

        }
        menuItem.setChecked(true);
        drawerLayout.closeDrawer(GravityCompat.START);
        return true;
    }


    @Override
    public boolean onSupportNavigateUp() {
        return NavigationUI.navigateUp(Navigation.findNavController(this,R.id.nav_host_fragment),drawerLayout);
    }

    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()){

            case android.R.id.home:
                if(drawerLayout.isDrawerOpen(GravityCompat.START)){
                    drawerLayout.closeDrawer(GravityCompat.START);
                    return true;
                }
                else{
                    return false;
                }
        }

        return super.onOptionsItemSelected(item);
    }
}

活动主

<?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">

      <!--  <fragment
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            app:navGraph="@navigation/navigation_graph"
            app:defaultNavHost="true"
            />
-->

    <fragment
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:defaultNavHost="true"
        app:navGraph="@navigation/navigation_graph" />


        <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="@color/colorPrimary"
                android:theme="@style/ThemeOverlay.AppCompat.Dark" />


        </LinearLayout>

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/navigationView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        android:background="@color/colorPrimary"
        android:theme="@style/ThemeOverlay.AppCompat.Dark">

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <include layout="@layout/nav_header" />

            <!-- <LinearLayout
                 android:layout_width="0dp"
                 android:layout_height="wrap_content"

                 android:layout_marginStart="8dp"
                 android:layout_marginTop="32dp"
                 android:layout_marginEnd="8dp"
                 android:orientation="vertical"
                 app:layout_constraintEnd_toEndOf="parent"
                 app:layout_constraintStart_toStartOf="parent"
                 app:layout_constraintTop_toBottomOf="@+id/textView9">-->

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="@color/colorPrimary"
                android:orientation="vertical">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="3"
                    android:orientation="horizontal">

                    <TextView
                        android:id="@+id/nav_profile"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_margin="4dp"
                        android:layout_weight="1"
                        android:clickable="true"
                        android:drawableTop="@drawable/profile_new"
                        android:foreground="?selectableItemBackground"
                        android:gravity="center"
                        android:padding="16dp"
                        android:text="@string/profile"
                        android:textAllCaps="true"
                        android:textAppearance="@style/TextAppearance.Menu.Item"
                        android:textSize="14sp" />

                    <TextView
                        android:id="@+id/start_new_session"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_margin="4dp"
                        android:layout_weight="1"
                        android:clickable="true"
                        android:drawableTop="@drawable/start_new_session_new"
                        android:drawablePadding="8dp"
                        android:foreground="?selectableItemBackground"
                        android:gravity="center"
                        android:padding="16dp"
                        android:text="@string/start_new_session"
                        android:textAppearance="@style/TextAppearance.Menu.Item"
                        android:textSize="14sp" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="3"
                    android:orientation="horizontal">

                    <TextView
                        android:id="@+id/list_of_sessions"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_margin="4dp"
                        android:layout_weight="1"
                        android:clickable="true"
                        android:drawableTop="@drawable/list_of_sessions_new"
                        android:drawablePadding="8dp"
                        android:foreground="?selectableItemBackground"
                        android:gravity="center"
                        android:padding="16dp"
                        android:text="@string/list_of_sessions"
                        android:textAppearance="@style/TextAppearance.Menu.Item"
                        android:textSize="14sp" />

                    <TextView
                        android:id="@+id/settings"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_margin="4dp"
                        android:layout_weight="1"
                        android:clickable="true"
                        android:drawableTop="@drawable/settings_new"
                        android:drawablePadding="8dp"
                        android:foreground="?selectableItemBackground"
                        android:gravity="center"
                        android:padding="16dp"
                        android:text="@string/settings"
                        android:textAppearance="@style/TextAppearance.Menu.Item"
                        android:textSize="14sp" />
                </LinearLayout>
            </LinearLayout>
        </LinearLayout>

</ScrollView>

    </com.google.android.material.navigation.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>

抽屉菜单

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <group android:checkableBehavior="single">

        <item
            android:id="@+id/profile"
            android:icon="@drawable/profile_new"
            android:title="Profile" />

        <item
            android:id="@+id/list"

            android:title="List" />

        <item
            android:id="@+id/third"

            android:title="Start" />
        <item
            android:id="@+id/fourth"

            android:title="Settings" />

    </group>



</menu>

更新 Mainactivity.Java

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.navigation.NavController;
import androidx.navigation.NavOptions;
import androidx.navigation.Navigation;
import androidx.navigation.ui.NavigationUI;


import com.supplementapp.ui.profile.profileFragment;
import com.supplementapp.ui.list.list_of_sessions;
import com.google.android.material.navigation.NavigationView;

import butterknife.BindView;


public class MainActivity extends AppCompatActivity implements NavigationView.OnClickListener {

    private DrawerLayout drawerLayout;
    private NavigationView navigationView;
    private Toolbar toolbar;
    public NavController navController;
    @BindView(R.id.nav_profile)
    TextView nav_profile;


    @Override
    protected void onCreate(Bundle savedInstanceState) {



        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        drawerLayout = findViewById(R.id.drawer_layout);
        navigationView = findViewById(R.id.navigationView);

        Toolbar toolBar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolBar);
        ActionBar actionBar = getSupportActionBar();
        init();






    }

    private void init(){
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, drawerLayout);
        NavigationUI.setupWithNavController(navigationView, navController);
        navigationView.setOnClickListener(this);

    }



    @Override
    public void onClick(View view) {
        loadFragment(new homeFragment());
        int id = view.getId();
        switch (id) {

            case R.id.nav_profile: {

                loadFragment(new list_of_sessions());
                drawerLayout.closeDrawer(GravityCompat.START);


                break;
            }

        }

    }

    @SuppressLint("ResourceType")
    public void loadFragment(Fragment fragment) {
        // create a FragmentManager
        FragmentManager fm = getSupportFragmentManager();
        // create a FragmentTransaction to begin the transaction and replace the Fragment

        FragmentTransaction fragmentTransaction = fm.beginTransaction();
        // replace the FrameLayout with new Fragment
        fragmentTransaction.replace(R.id.home_fragment, fragment);
        fragmentTransaction.commit(); // save the changes
    }




    @Override
    public boolean onSupportNavigateUp() {
        return NavigationUI.navigateUp(Navigation.findNavController(this,R.id.nav_host_fragment),drawerLayout);
    }

    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()){

            case android.R.id.home:
                if(drawerLayout.isDrawerOpen(GravityCompat.START)){
                    drawerLayout.closeDrawer(GravityCompat.START);
                    return true;
                }
                else{
                    return false;
                }
        }

        return super.onOptionsItemSelected(item);
    }

}

标签: androidandroid-layoutandroid-fragmentsnavigation-drawerandroid-navigationview

解决方案


尝试使用此代码制作自定义导航抽屉。我已经使用回收器添加动态项目。在这段代码中,我完全自定义了导航抽屉。您也可以根据需要更改代码

代码

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.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:openDrawer="start">

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight=".28"
            android:background="#FFEB3B"
            android:gravity="bottom"
            android:orientation="vertical"
            android:paddingLeft="15dp"
            android:paddingBottom="15dp">

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">

                <de.hdodenhof.circleimageview.CircleImageView
                    android:id="@+id/navigation_user_img"
                    android:layout_width="65dp"
                    android:layout_height="65dp"
                    android:src="@drawable/ic_launcher_background" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/navigation_user_name_tv"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Thrilling Picks"
                    android:textColor="#504C4C"
                    android:textSize="17sp"
                    android:textStyle="italic" />

                <TextView
                    android:id="@+id/navigation_user_email_tv"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Last Name"
                    android:textColor="#000"
                    android:textSize="14sp" />
            </LinearLayout>

        </LinearLayout>

        <android.support.v4.widget.NestedScrollView
            android:id="@+id/navigation_nested"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight=".72"
            android:fillViewport="true">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical"
                android:padding="15dp">

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="#fff"
                    android:gravity="center_vertical"
                    android:paddingTop="10dp"
                    android:paddingBottom="10dp">

                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="15dp"
                        android:src="@drawable/ic_menu_camera" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="20dp"
                        android:text="Camera"
                        android:textColor="#000"
                        android:textSize="14sp" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <android.support.v7.widget.RecyclerView
                        android:id="@+id/menu_recyler"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_marginBottom="5dp"
                        android:paddingLeft="15dp"
                        android:scrollbars="none" />
                </LinearLayout>

                <View
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:layout_marginTop="20dp"
                    android:background="#C4C4C4" />

                <TextView
                    android:id="@+id/invite_friends_tv"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="20dp"
                    android:drawableLeft="@drawable/ic_menu_share"
                    android:drawablePadding="20dp"
                    android:paddingLeft="15dp"
                    android:text="Invite Friends"
                    android:textColor="#000"
                    android:textSize="15sp" />

                <TextView
                    android:id="@+id/cards_tv"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="20dp"
                    android:drawableLeft="@drawable/ic_menu_gallery"
                    android:drawablePadding="20dp"
                    android:paddingLeft="15sp"
                    android:text="Gallery"
                    android:textColor="#000"
                    android:textSize="15sp" />

                <RelativeLayout
                    android:id="@+id/my_account_rl"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="20dp">

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:drawableLeft="@drawable/ic_menu_send"
                        android:drawablePadding="20dp"
                        android:paddingLeft="15sp"
                        android:text="Message"
                        android:textColor="#000"
                        android:textSize="15sp" />

                </RelativeLayout>

            </LinearLayout>
        </android.support.v4.widget.NestedScrollView>

    </LinearLayout>

</android.support.design.widget.NavigationView>

</android.support.v4.widget.DrawerLayout>

MainActivity.Java

请按照以下步骤在菜单项单击上加载片段

TextView invite_friends_tv;

//initialize view
invite_friends_tv = findViewById(R.id.invite_friends_tv);
//implement click listener
invite_friends_tv.setOnClickListener(this);

 //load default fragment 
 loadFragment(new BrowseDetailsFragment());
    home_page_title_tv.setText("Browse Details");
    home_user_iv.setVisibility(View.VISIBLE);

 @Override
public void onClick(View view) {
    switch (view.getId()) {
case R.id.nev_investments_tv:
            loadFragment(new InviteFriendFragment());

            drawer.closeDrawer(GravityCompat.START);
            break;
            }
            }

 /*---load and replace fragment---*/
@SuppressLint("ResourceType")
  public void loadFragment(Fragment fragment) {
    // create a FragmentManager
    FragmentManager fm = getSupportFragmentManager();
    // create a FragmentTransaction to begin the transaction and replace the 
    Fragment
    FragmentTransaction fragmentTransaction = fm.beginTransaction();
    // replace the FrameLayout with new Fragment
    fragmentTransaction.replace(R.id.home_container, fragment);
    fragmentTransaction.commit(); // save the changes
  }

在此处输入图像描述


推荐阅读