使用MaterialDrawer导航到片段

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用MaterialDrawer导航到片段相关的知识,希望对你有一定的参考价值。

我创建了一个新的android Studio项目,我已经实现了基于Github项目的导航抽屉(qazxsw poi)

到目前为止,一切都很好,但我唯一的问题是碎片之间的导航无法正常工作。

我希望抽屉里的每个项目都打开一个单独的片段。

这是我的MainActivity.java

Mike Penz

这是我的activity_main.xml

package com.senseidev.isensei.activities;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import com.mikepenz.fontawesome_typeface_library.FontAwesome;
import com.mikepenz.google_material_typeface_library.GoogleMaterial;
import com.mikepenz.iconics.IconicsDrawable;
import com.mikepenz.materialdrawer.AccountHeader;
import com.mikepenz.materialdrawer.AccountHeaderBuilder;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.model.ProfileDrawerItem;
import com.mikepenz.materialdrawer.model.ProfileSettingDrawerItem;
import com.mikepenz.materialdrawer.model.SecondaryDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IProfile;
import com.senseidev.isensei.R;
import com.senseidev.isensei.fragments.HomeFragment;
import com.senseidev.isensei.fragments.PhotosFragment;
import com.senseidev.isensei.fragments.ProductsFragment;
import com.senseidev.isensei.fragments.ProfileFragment;
import com.senseidev.isensei.fragments.ServicesFragment;

public class MainActivity extends AppCompatActivity {

    private static final int PROFILE_SETTING = 1;
    private Toolbar mainToolbar;
    private AccountHeader headerResult = null;
    private Drawer result = null;

    private IProfile profile_1;
    private IProfile profile_2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mainToolbar = (Toolbar) findViewById(R.id.main_toolbar);
        setSupportActionBar(mainToolbar);
        getSupportActionBar().setTitle(R.string.app_name);

        profile_1 = new ProfileDrawerItem().withName("Dev").withEmail("developer@gmail.com").withIcon(getResources().getDrawable(R.drawable.ip_user_bi_photo));
        profile_2 = new ProfileDrawerItem().withName("Isen").withEmail("isen@gmail.com").withIcon(getResources().getDrawable(R.drawable.ip_user_bi_photo));

        // Create the AccountHeader
        buildHeader(false, savedInstanceState);

        //create the drawer and remember the `Drawer` result object
        result = new DrawerBuilder()
                .withActivity(this)
                .withAccountHeader(headerResult)
                .withToolbar(mainToolbar)
                .addDrawerItems(
                        new SecondaryDrawerItem().withName(R.string.drawer_profile)
                                .withSelectedIconColor(ContextCompat.getColor(this, R.color.app_belize)).withIconTintingEnabled(true)
                                .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_account_box).actionBar().colorRes(R.color.material_drawer_dark_primary_text))
                                .withTag("Bullhorn"),

                        new SecondaryDrawerItem().withName(R.string.drawer_services)
                                .withSelectedIconColor(ContextCompat.getColor(this, R.color.app_belize)).withIconTintingEnabled(true)
                                .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_device_hub).actionBar().colorRes(R.color.material_drawer_dark_primary_text))
                                .withTag("Bullhorn"),

                        new SecondaryDrawerItem().withName(R.string.drawer_products)
                                .withSelectedIconColor(ContextCompat.getColor(this, R.color.app_belize)).withIconTintingEnabled(true)
                                .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_shopping_cart).actionBar().colorRes(R.color.material_drawer_dark_primary_text))
                                .withTag("Bullhorn"),

                        new SecondaryDrawerItem().withName(R.string.drawer_images)
                                .withSelectedIconColor(ContextCompat.getColor(this, R.color.app_belize)).withIconTintingEnabled(true)
                                .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_camera_roll).actionBar().colorRes(R.color.material_drawer_dark_primary_text))
                                .withTag("Bullhorn")



                )
                .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                    @Override
                    public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
                        // do something with the clicked item :D

                        selectDrawerItem((int) drawerItem.getIdentifier(), drawerItem);

                        return true;
                    }
                })
                .addStickyDrawerItems(
                        new SecondaryDrawerItem().withName(R.string.drawer_all_right_reserved).withIcon(FontAwesome.Icon.faw_copyright).withEnabled(false)
                ).build();

    }


    /**
     * small helper method to reuse the logic to build the AccountHeader
     * this will be used to replace the header of the drawer with a compact/normal header
     *
     * @param compact
     * @param savedInstanceState
     */
    private void buildHeader(boolean compact, Bundle savedInstanceState) {
        headerResult = new AccountHeaderBuilder()
                .withActivity(this)
                .withHeaderBackground(R.drawable.ip_menu_header_bg)
                .withCompactStyle(compact)
                .addProfiles(
                        profile_1,
                        profile_2,

                        new ProfileSettingDrawerItem()
                                .withName("Add Account")
                                .withDescription("Add new GitHub Account")
                                .withIcon(new IconicsDrawable(this, GoogleMaterial.Icon.gmd_add)
                                        .actionBar().paddingDp(5).colorRes(R.color.material_drawer_dark_primary_text)).withIdentifier(PROFILE_SETTING),
                        new ProfileSettingDrawerItem().withName("Manage Account").withIcon(GoogleMaterial.Icon.gmd_settings)
                )
                .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() {
                    @Override
                    public boolean onProfileChanged(View view, IProfile profile, boolean current) {
                        //sample usage of the onProfileChanged listener
                        //if the clicked item has the identifier 1 add a new profile ;)
                        if (profile instanceof IDrawerItem && ((IDrawerItem) profile).getIdentifier() == PROFILE_SETTING) {
                            IProfile newProfile = new ProfileDrawerItem()
                                    .withNameShown(true)
                                    .withName("Kensei")
                                    .withEmail("kensei@gmail.com")
                                    .withIcon(getResources().getDrawable(R.drawable.ip_user_bi_photo));
                            if (headerResult.getProfiles() != null) {
                                //we know that there are 2 setting elements. set the new profile above them ;)
                                headerResult.addProfile(newProfile, headerResult.getProfiles().size() - 2);
                            } else {
                                headerResult.addProfiles(newProfile);
                            }
                        }

                        //false if you have not consumed the event and it should close the drawer
                        return false;
                    }
                })
                .build();
    }

    public void selectDrawerItem(int ItemId, IDrawerItem drawerItem) {
        // Create a new fragment and specify the fragment to show based on nav item clicked
        Fragment fragment = null;
        Class fragmentClass;
        switch (ItemId) {

            case 1:
                fragmentClass = ProfileFragment.class;
                break;

            case 2:
                fragmentClass = ServicesFragment.class;
                break;

            case 3:
                fragmentClass = ProductsFragment.class;
                break;

            case 4:
                fragmentClass = PhotosFragment.class;
                break;

            default:
                fragmentClass = HomeFragment.class;
        }
        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // Insert the fragment by replacing any existing fragment
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
        result.closeDrawer();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {

            default:
                return super.onOptionsItemSelected(item);
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //add the values which need to be saved from the drawer to the bundle
        outState = result.saveInstanceState(outState);
        //add the values which need to be saved from the accountHeader to the bundle
        outState = headerResult.saveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {
        //handle the back press :D close the drawer first and if the drawer is closed close the activity
        if (result != null && result.isDrawerOpen()) {
            result.closeDrawer();
        } else {
            super.onBackPressed();
        }
    }

}

这是我的HomeFragment.java

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="com.senseidev.isensei.activities.MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/main_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?android:attr/actionBarSize"
        android:background="@color/colorPrimary">

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

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

    </FrameLayout>

</RelativeLayout>

这是我的fragment_home.xml

package com.project.app.fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.project.app.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class HomeFragment extends Fragment {


    public HomeFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

       View view = inflater.inflate(R.layout.fragment_home, container, false);
       return view;
    }

}
答案

您的XLM活动布局应首先具有framelayout插槽,以便添加和替换您的片段。

添加这个新方法,该方法将负责根据从抽屉中选择的项目ID创建片段并将其添加到活动中:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.senseidev.isensei.fragments.HomeFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical"
        android:text="HOME" />

</FrameLayout>

从withOnDrawerItemClickListener调用此方法,如下所示:

public void selectDrawerItem(int ItemId,IDrawerItem drawerItem) {
    // Create a new fragment and specify the fragment to show based on nav item clicked
    Fragment fragment = null;
    Class fragmentClass;
    switch(ItemId) {
        case 1:
            fragmentClass = PageFragment2.class;
            break;
        case 2:
            fragmentClass = PageFragment2.class;
            break;
         default:
            fragmentClass = PageFragment2.class;
    }
    try {
        fragment = (Fragment) fragmentClass.newInstance();
    } catch (Exception e) {
        e.printStackTrace();
    }
    // Insert the fragment by replacing any existing fragment
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
    result.closeDrawer();
} 

这可能无法模拟要求,但会为您提供逻辑,祝您好运。

添加.withIdentifier()

         .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() {
                @Override
                public boolean onItemClick(View view, int position, IDrawerItem drawerItem)
                {
                    // do something with the clicked item :D

                    selectDrawerItem((int)drawerItem.getIdentifier(), drawerItem);
                    return true;
                }
            })

以上是关于使用MaterialDrawer导航到片段的主要内容,如果未能解决你的问题,请参考以下文章

使用 NavController 从片段导航到另一个片段

导航抽屉活动:在按钮单击时从片段移动到片段

防止导航到同一个片段

将 Butterknife 与 BaseActivity/Child 活动和 MaterialDrawer 一起使用

FAB 的片段布局与 CoordinatorLayout 冲突

如何从一个片段导航到另一个片段?