如何在菜单抽屉上调用片段?

时间:2019-08-29 18:21:26

标签: java android

我是android的新手,我正在制作带有YouTube教程,android.com,stackoverflow等用于trainig的字典应用。现在我有一个关于主抽屉的问题。我将尝试用图片解释。

https://i.imgur.com/s9EjAna.jpg

当我启动该应用程序时,打开字典页面很不错。当我单击书签时,书签页面也将打开,但是当我在书签页面并单击词典链接时,词典页面不会打开。

这里是我的代码,我为书签和字典页面使用了相同的代码。

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        if (id == R.id.nav_bookmark){

            String activeFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();
            if (!activeFragment.equals(BookmarkFragment.class.getSimpleName())){

            goToFragment(bookmarkFragment, false);
            }
        }

        if (id == R.id.nav_dict){

            String activeFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();
            if (!activeFragment.equals(BookmarkFragment.class.getSimpleName())){

                goToFragment(dictionaryFragment, false);
            }
        }

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

但是我认为(这只是一个猜测,我不确定)问题是此代码

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

我所有的MainActivity.java都在这里

package com.example.dict;

import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.WindowManager;


import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import androidx.annotation.RequiresApi;
import androidx.core.view.GravityCompat;
import androidx.appcompat.app.ActionBarDrawerToggle;

import android.view.MenuItem;

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

import androidx.drawerlayout.widget.DrawerLayout;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.view.Menu;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    MenuItem menuSetting;
    Toolbar toolbar;


    DBHelper dbHelper;

    DictionaryFragment dictionaryFragment;
    BookmarkFragment bookmarkFragment;

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

        dbHelper = new DBHelper(this);

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

        dictionaryFragment = new DictionaryFragment();
        bookmarkFragment = BookmarkFragment.getInstance(dbHelper);
        goToFragment(dictionaryFragment, true);

        dictionaryFragment.setOnFragmentListener(new FragmentListener() {
            @Override
            public void onItemClick(String value) {
                String id =  Global.getState(MainActivity.this,"dict_type");
                int dicType = id == null? R.id.eng_kh:Integer.valueOf(id);
                goToFragment(DetailFragment.getNewInstance(value, dbHelper, dicType), false);
            }
        });
        bookmarkFragment.setOnFragmentListener(new FragmentListener() {
            @Override
            public void onItemClick(String value) {

                String id =  Global.getState(MainActivity.this,"dict_type");
                int dicType = id == null? R.id.eng_kh:Integer.valueOf(id);
                goToFragment(DetailFragment.getNewInstance(value, dbHelper, dicType), false);
            }
        });

        EditText edit_search  = findViewById(R.id.edit_search);
        edit_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                dictionaryFragment.filterValue(charSequence.toString());
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

    }

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

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        super.onCreateOptionsMenu(menu);
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        menuSetting = menu.findItem(R.id.action_settings);

    String id =  Global.getState(this,"dict_type");
    if (id != null)
        onOptionsItemSelected(menu.findItem(Integer.valueOf(id)));

    else {
        ArrayList<String> source =dbHelper.getWord(R.id.eng_kh);
    dictionaryFragment.resetDatasource(source);


    }
        return true;
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @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.eng_kh) {
            Global.saveState(this, "dict_type", String.valueOf(id));
            ArrayList<String> source = dbHelper.getWord(id);
            dictionaryFragment.resetDatasource(source);
            menuSetting.setIcon(getDrawable(R.drawable.ic_lang));
            return true;

        } else if (id==R.id.kh_eng){
            Global.saveState(this, "dict_type", String.valueOf(id));
            ArrayList<String> source = dbHelper.getWord(id);
            dictionaryFragment.resetDatasource(source);
            menuSetting.setIcon(getDrawable(R.drawable.ic_lang2));
            return true;

        }   else if (id==R.id.kh_kh){
            Global.saveState(this, "dict_type", String.valueOf(id));
            ArrayList<String> source = dbHelper.getWord(id);
            dictionaryFragment.resetDatasource(source);
            menuSetting.setIcon(getDrawable(R.drawable.ic_lang3));
            return true;
        }


        return super.onOptionsItemSelected(item);
    }

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

            String activeFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();
            if (!activeFragment.equals(BookmarkFragment.class.getSimpleName())){

            goToFragment(bookmarkFragment, false);
            }
        }

        if (id == R.id.nav_dict){

            String activeFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();
            if (!activeFragment.equals(BookmarkFragment.class.getSimpleName())){

                goToFragment(dictionaryFragment, false);
            }
        }

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




    void goToFragment(Fragment fragment, boolean isTop){

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();


        fragmentTransaction.replace(R.id.fragment_container, fragment);
        if (!isTop)
            fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }


    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {

        String activeFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();
        if (activeFragment.equals(BookmarkFragment.class.getSimpleName())){
            menuSetting.setVisible(false);
            toolbar.findViewById(R.id.edit_search).setVisibility(View.GONE);
            toolbar.setTitle("Bookmark");
        }else  {
            menuSetting.setVisible(true);
            toolbar.findViewById(R.id.edit_search).setVisibility(View.VISIBLE);
            toolbar.setTitle("");
        }
        return true;
    }
}


我的activity_main_drawer在这里

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



    <item android:title="Network">
        <menu>

            <item
                android:id="@+id/nav_dict"
                android:icon="@drawable/ic_dict"
                android:title="Dictionary"/>

            <item
                android:id="@+id/nav_bookmark"
                android:icon="@drawable/ic_bookmark"
                android:title="@string/menu_bookmark" />

            <item
                android:id="@+id/nav_rate"
                android:icon="@drawable/ic_thumb"
                android:title="@string/menu_rate" />

            <item
                android:id="@+id/nav_share"
                android:icon="@drawable/ic_menu_share"
                android:title="@string/menu_share" />

        </menu>
    </item>
    <item android:title="Other">
        <menu>

            <item
                android:id="@+id/nav_help"
                android:icon="@drawable/ic_help"
                android:title="@string/menu_help" />

            <item
                android:id="@+id/nav_about"
                android:icon="@drawable/ic_info"
                android:title="@string/menu_about" />

        </menu>
    </item>

</menu>


如果您需要更多代码,我可以粘贴在这里。谢谢。

1 个答案:

答案 0 :(得分:0)

onNavigationItemSelected内,单击“字典”时,您正在检查BookmarkFragment。应该是DictionaryFragment

更新代码

if (id == R.id.nav_dict){

        String activeFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container).getClass().getSimpleName();
        if (!activeFragment.equals(DictionaryFragment.class.getSimpleName())){

            goToFragment(dictionaryFragment, false);
        }
    }