Меню навигации и кнопка добавления на выборочных фрагментах в android - PullRequest
0 голосов
/ 22 января 2020

Мне нужна ваша помощь, чтобы понять концепцию меню в android. Я использую навигационное меню (панель) в android и загружаю его в MainActivity и помещаю три разных фрагмента.

При запуске приложения открывается навигационное меню и фрагмент по умолчанию также загружается, как указано ниже.

enter image description here

Здесь все в порядке, но когда я нажимаю на третий пункт меню (Кредитные карты), затем открывается фрагмент в этом фрагменте, я использую ListView, как упоминалось ниже:

enter image description here

Теперь я хочу добавить кнопку на панели, здесь вы можете увидеть ее под панелью. Как я могу достичь этого? пожалуйста, помогите мне. Здесь я хочу значок бургера для навигации слева и добавьте значок / кнопку справа на той же панели.

Примечание: я пытался добавить кнопку на панели инструментов, которую я использую, внутри DrawerLayout, но эта кнопка появляется на всех фрагментах.

Вот код для activity_main. xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.ac 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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:id="@+id/drawer_layout"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

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

        <android.support.v7.widget.Toolbar
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary"
            android:id="@+id/toolbar"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            >
        </android.support.v7.widget.Toolbar>

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/fragement_container"/>

    </LinearLayout>

    <android.support.design.widget.NavigationView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:id="@+id/nav_view"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/drawer_menu" >
    </android.support.design.widget.NavigationView>

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

MainActivity. java

package com.mas.mas;

import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private DrawerLayout drawerLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        drawerLayout = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

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

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container, new TransactionsListFragment()).commit();
            setTitle("Transactions");
            navigationView.setCheckedItem(R.id.transactions);
        }
    }

    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
            drawerLayout.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem menuItem) {
        switch (menuItem.getItemId()) {
            case R.id.transactions:
                getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container, new TransactionsListFragment()).commit();
                setTitle("Email");
                break;
            case R.id.banks:
//                getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container, new MessageFragement()).commit();
                setTitle("Banks");
                break;
            case R.id.cards:
                setTitle("Cards");
                getSupportFragmentManager().beginTransaction().replace(R.id.fragement_container, new CardsFragment()).commit();
                break;
        }
        drawerLayout.closeDrawer(GravityCompat.START);
        return true;
    }
}

Спасибо.

1 Ответ

0 голосов
/ 22 января 2020

Добавить кнопку на панели инструментов в mainActivity

<androidx.appcompat.widget.Toolbar

        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

        <ImageView

            android:id="@+id/adimage"
            android:layout_marginBottom="@dimen/padd_10"
            android:layout_marginTop="@dimen/padd_10"
            android:layout_alignParentRight="true"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ad"></ImageView>
        </RelativeLayout>

, затем использовать ее для onClick Listner в mainActivity. java

Toolbar toolbar = findViewById(R.id.toolbar);
adsImageView=toolbar.findViewById(R.id.adimage);

adsImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

}

надеюсь, что это поможет

...