Реализация панели инструментов в навигационном представлении на основе действий - PullRequest
0 голосов
/ 11 октября 2018

Я пытаюсь реализовать панель инструментов с ActionBarDrawerToggle в моем приложении.Я реализовал NavigationActivity и добавил Activites в свой проект, который я также реализовал как NavigationActivities, но позже отредактировал их в соответствии с ситуацией.

Лучший способ объяснить это - показать вам код и ошибки, которые яПодумайте.

То, что у меня есть, является в основном нетронутой навигационной активностью:

package edmt.dev.androidgridlayout;

import android.content.Intent;
import android.nfc.Tag;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.util.Log;
import android.view.View;
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.Menu;
import android.view.MenuItem;

import java.util.ArrayList;

public class NavigationActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

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

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

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

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();


        switch (id) {
            case R.id.drawerHeros:
                Intent intentHeros = new Intent(this, heroActivity.class);
                startActivity(intentHeros);
                break;
            case R.id.drawerSpells:
                Intent intentSpells = new Intent (this, spellActivity.class);
                startActivity(intentSpells);
                break;
            case R.id.drawerItems:
                Intent intentItems = new Intent (this, itemActivity.class);
                startActivity(intentItems);
                break;
            case R.id.drawerImprovements:
                Intent intentImpr = new Intent (this, improvementActivity.class);
                startActivity(intentImpr);
                break;
            case R.id.drawerCreeps:
                Intent intentCreeps = new Intent (this, creepActivity.class);
                startActivity(intentCreeps);
                break;

        }

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

Чем я показываю вам один из реализованных мною Activites (heroActivity):

public class heroActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private SwitchCompat switchHeros;
    List<Heros> listHeros;

    AppCompatSpinner spinnerHeros;
    private xCustomSpinnerAdapater spinnerAdapter;
    private String[] spinnerNames = {"All", "Black", "Blue", "Green", "Red"};
    private  int[] spinnerImages = {R.drawable.artifact, R.drawable.black, R.drawable.blue, R.drawable.green, R.drawable.red};
    private Toast spinnerToast;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hero);
        Toolbar toolbar = (findViewById(R.id.toolbar)); // this is fine since there is only app_bar_navigation */
        setSupportActionBar(toolbar);


        FloatingActionButton fab = findViewById(R.id.fab); // that is the button for e-mail -> is fine -> app_bar_navigation */
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = findViewById(R.id.drawer_layout_hero);
        final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view_hero);
        navigationView.setNavigationItemSelectedListener(this);


/* Make ----------- Content_Hero ----------------*/
        setContentView(R.layout.content_hero);
        spinnerHeros = findViewById(R.id.heroSpinner);
        switchHeros = findViewById(R.id.switchHeros);



        /*Spinner: */
        spinnerAdapter = new xCustomSpinnerAdapater(this, spinnerNames,spinnerImages);
        spinnerHeros.setAdapter(spinnerAdapter);

        spinnerHeros.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {

                if(spinnerToast !=  null){
                    spinnerToast.cancel();
                }
                spinnerToast.makeText(getApplicationContext(),"Category: " + spinnerNames[i] + " is shown.",Toast.LENGTH_SHORT).show();
                getHeroList(spinnerHeros.getSelectedItem().toString(),switchHeros.isChecked());
                RecyclerView rvHeros = findViewById(R.id.recycler_heros);
                RecyclerViewAdapterHero newAdapterHeros = new RecyclerViewAdapterHero(heroActivity.this, listHeros);
                rvHeros.setLayoutManager(new GridLayoutManager(heroActivity.this,3));
                rvHeros.setAdapter(newAdapterHeros);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                getHeroList(spinnerHeros.getSelectedItem().toString(),switchHeros.isChecked());
                RecyclerView rvHeros = findViewById(R.id.recycler_heros);
                RecyclerViewAdapterHero newAdapterHeros = new RecyclerViewAdapterHero(heroActivity.this, listHeros);
                rvHeros.setLayoutManager(new GridLayoutManager(heroActivity.this,3));
                rvHeros.setAdapter(newAdapterHeros);
            }
        });


        // Load everything ones.
        getHeroList(spinnerHeros.getSelectedItem().toString(),switchHeros.isChecked());
        RecyclerView rvHeros = findViewById(R.id.recycler_heros);
        RecyclerViewAdapterHero newAdapterHeros = new   RecyclerViewAdapterHero(heroActivity.this, listHeros);
        rvHeros.setLayoutManager(new GridLayoutManager(heroActivity.this,3));
        rvHeros.setAdapter(newAdapterHeros);

        /*--- Switch ---*/


        switchHeros.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getHeroList(spinnerHeros.getSelectedItem().toString(),switchHeros.isChecked());
                RecyclerView rvHeros = findViewById(R.id.recycler_heros);
                RecyclerViewAdapterHero newAdapterHeros = new RecyclerViewAdapterHero(heroActivity.this, listHeros);
                rvHeros.setLayoutManager(new GridLayoutManager(heroActivity.this,3));
                rvHeros.setAdapter(newAdapterHeros);
            }
        });



    }

    private void getHeroList(String chosenCategory, Boolean switchStatus) {


        listHeros = new ArrayList<>();

        switch(chosenCategory){
            case "All":
                if(switchStatus != true){
                    listHeros.add(new Heros(R.drawable.bloodseeker,"Bloodseeker", "7", "0", "6", "<b>Blood Bath:</b> <br />Fully heal Bloodseeker after a unit blocking it dies.", "black", R.drawable.blood_rage, "Blood rage", "Silence a unit this round. Give that unit +4 Attack this round.", R.drawable.artifact_big, "", "This is boosters hero", "My homeland is a place of beauty and grace... of crystal streams and bountiful harvest... it is undeniably a gift from the gods. But when such a gift is bestowed upon you, it is right to give thanks... and there is only one way to show gratitude to the Flayed Twins. With blood.<br />— Strygwyr, the Bloodseeker", "Rare"));
                    [..many more..]

        }


    }

    @Override
    public void onBackPressed() {
        setContentView(R.layout.activity_hero);
        DrawerLayout drawer =  findViewById(R.id.drawer_layout_hero);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        setContentView(R.layout.activity_hero);
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.navigation, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        setContentView(R.layout.activity_hero);
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        setContentView(R.layout.activity_hero);
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        switch (id) {
            case R.id.drawerHeros:
                Intent intentHeros = new Intent(this, heroActivity.class);
                startActivity(intentHeros);
                break;
            case R.id.drawerSpells:
                Intent intentSpells = new Intent (this, spellActivity.class);
                startActivity(intentSpells);
                break;
            case R.id.drawerItems:
                Intent intentItems = new Intent (this, itemActivity.class);
                startActivity(intentItems);
                break;
            case R.id.drawerImprovements:
                Intent intentImpr = new Intent (this, improvementActivity.class);
                startActivity(intentImpr);
                break;
            case R.id.drawerCreeps:
                Intent intentCreeps = new Intent (this, creepActivity.class);
                startActivity(intentCreeps);
                break;

        }

        DrawerLayout drawer = findViewById(R.id.drawer_layout_hero);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

Я не думаю, что RecyclerView добавляет какое-либо значение к сообщению, поэтому я опускаю это.

Теперь взгляните на мои 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_hero"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:openDrawer="start">

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

        <android.support.design.widget.NavigationView
            android:id="@+id/nav_view_hero"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:fitsSystemWindows="true"
            app:headerLayout="@layout/nav_header_navigation"
            app:menu="@menu/activity_navigation_drawer" />

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

HeroActivity использует в основном мое первоереализовал NavigationView.Таким образом, я могу один раз отредактировать свои инструменты навигации, такие как NavigationDrawer, и я изменю все виды деятельности.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 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/constraintLayoutHeros"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context=".heroActivity"

        android:padding="8dp"
        android:background="@drawable/background"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
    <android.support.design.widget.AppBarLayout
            android:id="@+id/heroAppbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fitsSystemWindows="true"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            >

            <android.support.v7.widget.Toolbar
                android:id="@+id/heroToolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay" />

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

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="30dp"

                android:layout_marginTop="15dp"
                android:layout_marginBottom="5dp"

                android:text="Heros in Artifact"
                android:textSize="22sp"
                android:textStyle="bold"
                android:layout_gravity="center"
                android:textColor="#fff"
                />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"

                android:layout_marginBottom="20dp"

                android:textColor="#fff"
                android:textSize="15sp"
                android:text="Here will be the introduction to the hero page.."
                />

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

                android:orientation="horizontal"
                android:weightSum="2"

                android:background="#fff"

                >
                <android.support.v7.widget.AppCompatSpinner
                    android:id="@+id/heroSpinner"

                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:layout_marginStart="10dp"
                    android:layout_marginEnd="10dp"

                    android:dropDownWidth="match_parent"
                    android:spinnerMode="dropdown"
                    android:popupBackground="#fff"
                    android:background="#8A8A8A"

                    />




                <android.support.v7.widget.SwitchCompat
                    android:id="@+id/switchHeros"

                    android:layout_width="0dp"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:layout_marginStart="20dp"
                    android:layout_marginEnd="20dp"
                    android:layout_gravity="center"

                    android:background="#8A8A8A"

                    android:checked="false"
                    />


            </LinearLayout>

        </LinearLayout>

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_heros"
            android:layout_width="match_parent"
            android:layout_height="match_parent">


        </android.support.v7.widget.RecyclerView>

    </LinearLayout>

Это файл contentHero.xml, который редактируется в моем файле heroActivity.В основном я хочу реализовать панель инструментов в этом представлении.Как вы можете видеть, я пытался реализовать другую панель инструментов в этом контексте, но как только я пытаюсь установить heroToolbar в моем heroActivity на setSupportActionBar, я получаю ошибку nullPointer.

Есть ли разумный способ сделатьэто, может быть, используя первоначальный NavigationView для этого или просто правильно реализовать панель инструментов?

С наилучшими пожеланиями CG

...