Как использовать Navigation Drawer и Bottom Navigation в одном приложении Android - PullRequest
0 голосов
/ 17 марта 2020

Я недавно новичок в Android Studio и пытаюсь создать приложение лояльности для бизнеса. Для приложения будет 2 группы пользователей, учетная запись владельца, а затем несколько учетных записей клиентов. Я пытаюсь создать отдельные меню навигации для каждой группы пользователей. Владелец, имеющий нижнюю навигацию, и клиенты, имеющие навигационный ящик. Я успешно смог реализовать навигационный ящик, используя активность навигационного ящика в Android.

NavigationMain Java Класс:

public class NavigationMainCustomers extends AppCompatActivity
{

     DatabaseReference databaseReference;
     FirebaseUser firebaseUser;
     FirebaseAuth firebaseAuth;
     String userID;
     TextView txtuserEmail, txtUsersName;

    private AppBarConfiguration mAppBarConfiguration;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_navigation_main);
        Toolbar toolbar = findViewById(R.id.toolbar);

        firebaseAuth = FirebaseAuth.getInstance();
        userID = firebaseAuth.getUid();

        databaseReference = FirebaseDatabase.getInstance().getReference().child("Customers").child(userID);

        setSupportActionBar(toolbar);

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        View headerView = navigationView.getHeaderView(0);

        txtuserEmail = headerView.findViewById(R.id.txtUserEmail);
        txtUsersName = headerView.findViewById(R.id.txtUsersName);

        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_loyalty_card, R.id.nav_voucher,
                R.id.nav_chat, R.id.nav_our_products, R.id.nav_about_us,
                R.id.nav_location, R.id.nav_faq, R.id.nav_barcode_scanner, R.id.nav_customer_data)
                .setDrawerLayout(drawer)
                .build();

        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        databaseReference.addValueEventListener(new ValueEventListener()
        {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot)
            {
                // Retrieve users email and name
                String email = dataSnapshot.child("email").getValue().toString();
                String firstName = dataSnapshot.child("firstName").getValue().toString();
                String surname = dataSnapshot.child("surname").getValue().toString();

                //Set header textviews to current user data
                txtuserEmail.setText(email);
                txtUsersName.setText(firstName + " " + surname);

            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError)
            {
                System.out.println("The read failed: " + databaseError.getCode());

            }
        });
        return true;
    }

    @Override
    public boolean onSupportNavigateUp()
    {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);

        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();

    }

}

activity_navigation_main. 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:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        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"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />


</androidx.drawerlayout.widget.DrawerLayout>

mobile_navigation. xml

<?xml version="1.0" encoding="utf-8"?>
<navigation 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/mobile_navigation"
    app:startDestination="@+id/nav_home">

    <fragment
        android:id="@+id/nav_home"
        android:name="com.alicearmstrong.coffeysloyaltyrecent.uiCustomers.home.HomeFragment"
        android:label="@string/menu_home"
        tools:layout="@layout/fragment_home_customer" />

    <fragment
        android:id="@+id/nav_loyalty_card"
        android:name="com.alicearmstrong.coffeysloyaltyrecent.uiCustomers.loyaltycard.LoyaltyCardFragment"
        android:label="@string/menu_loyalty"
        tools:layout="@layout/fragment_loyalty_card_customers" />

    <fragment
        android:id="@+id/nav_voucher"
        android:name="com.alicearmstrong.coffeysloyaltyrecent.uiCustomers.voucher.VoucherFragment"
        android:label="@string/menu_voucher"
        tools:layout="@layout/fragment_voucher_customer" />

    <fragment
        android:id="@+id/nav_chat"
        android:name="com.alicearmstrong.coffeysloyaltyrecent.uiCustomers.chat.ChatFragment"
        android:label="@string/menu_chat"
        tools:layout="@layout/fragment_chat_customer" />

    <fragment
        android:id="@+id/nav_our_products"
        android:name="com.alicearmstrong.coffeysloyaltyrecent.uiCustomers.ourproducts.OurProductsFragment"
        android:label="@string/menu_products"
        tools:layout="@layout/fragment_our_products_customers" />

    <fragment
        android:id="@+id/nav_about_us"
        android:name="com.alicearmstrong.coffeysloyaltyrecent.uiCustomers.aboutus.AboutUsFragment"
        android:label="@string/menu_about_us"
        tools:layout="@layout/fragment_about_us_customer" />

    <fragment
    android:id="@+id/nav_location"
    android:name="com.alicearmstrong.coffeysloyaltyrecent.uiCustomers.location.LocationFragment"
    android:label="@string/menu_location"
    tools:layout="@layout/fragment_location_customer" />

    <fragment
        android:id="@+id/nav_faq"
        android:name="com.alicearmstrong.coffeysloyaltyrecent.uiCustomers.faq.FAQFragment"
        android:label="@string/menu_faq"
        tools:layout="@layout/fragment_faq_customer" />
    <fragment
        android:id="@+id/nav_logout"
        android:name="com.alicearmstrong.coffeysloyaltyrecent.uiCustomers.logout.ourproducts.LogoutFragment"
        android:label="@string/menu_faq"
        tools:layout="@layout/fragment_logout" />
</navigation>

I Я пытался использовать нижнюю навигацию android, но это вызывало проблемы с навигационным блоком. Буду признателен за любую помощь или совет!

1 Ответ

1 голос
/ 17 марта 2020

вы можете нам что-то вроде этого

BottomNavigationView bottomNavigation = findViewById(R.id.bottom_navigation);
Menu menu = bottomNavigation.getMenu();
if(caseOne){
menu.add(Menu.NONE, MENU_ITEM_ID_ONE, Menu.NONE, getString(R.string.str_menu_one))
    .setIcon(R.drawable.ic_action_one);
}else{
menu.add(Menu.NONE, MENU_ITEM_ID_TWO, Menu.NONE, getString(R.string.str_menu_two))
    .setIcon(R.drawable.ic_action_two);
}

заметьте, что идентификатор пункта меню должен совпадать с идентификатором фрагмента навигации

...