在基于活动的Navigationview中实现工具栏

时间:2018-10-11 14:46:55

标签: android xml navigationview

我正在努力通过ActionBarDrawerToggle将工具栏实现到我的App中。 我所做的是实现了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;
    }
}

比我向您展示我实现的一项活动(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中进行编辑。基本上,我想在此视图中实现工具栏。 如您所见,我试图在这种情况下实现另一个工具栏,但是当我尝试将heroActivity中的heroToolbar设置为setSupportActionBar时,就会出现nullPointer错误。

是否可以通过使用初始的NavigationView或正确实现工具栏来实现此目的?

致以最诚挚的问候 CG

0 个答案:

没有答案