2017-12-15 6 views
0

ich ein neuen Android-Studio-Projekt erstellt habe, und ich habe eine Navigationsleiste auf der Grundlage des Github Projekt (Mike Penz)Navigieren mit MaterialDrawer fragmentieren

Alles funktioniert großartig, so weit, aber mein einziges Problem ist, dass Navigation inplemented zwischen Fragmente funktionieren nicht.

Ich möchte jedes Element in der Schublade ein separates Fragment zu öffnen.

Das ist mein MainActivity.java

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("[email protected]").withIcon(getResources().getDrawable(R.drawable.ip_user_bi_photo)); 
     profile_2 = new ProfileDrawerItem().withName("Isen").withEmail("[email protected]m").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("[email protected]") 
            .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(); 
     } 
    } 

} 

Dieses

mein activity_main.xml ist
<?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> 

Das ist mein HomeFragment.java

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; 
    } 

} 

Das ist mein fragment_home.xml

<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> 

Antwort

0

Ihr XLM-Aktivitätslayout sollte zuerst einen Framlayout-Slot haben, damit Ihre Fragmente hinzugefügt und ersetzt werden können.

diese neue Methode hinzufügen, die die Erstellung und das Hinzufügen Ihrer Fragmente auf die Aktivität auf der Grundlage der Artikel-ID aus der Schublade ausgewählt verantwortlich sein wird:

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(); 
} 

Aufruf dieser Methode aus dem withOnDrawerItemClickListener wie folgt aus:

Dies kann nicht Anforderungen simulieren, aber Sie werden mit der Logik, viel Glück.

hinzufügen .withIdentifier()

.addDrawerItems(
        new SecondaryDrawerItem().withName(R.string.drawer_profile) 
          .withIdentifier(1) 
          .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"), 
+0

Danke für Ihre Hilfe - aber ich habe noch etwas Hilfe benötigen ich eine Framelayout zur (activity_main.xml) hinzugefügt haben, aber es gibt noch ein Problem, da es nicht Fragmente wechseln Ich habe meinen Code über – Jonas

+0

aktualisiert, woher wussten Sie, dass das Fragment nicht angezeigt wird? Dies kann nicht offensichtlich sein, es sei denn, jedes Fragment enthält verschiedene Dinge, wie verschiedene Hintergrundfarben oder die Textansicht, die Sie hinzugefügt haben, zeigen unterschiedliche Texte an, es zeigt immer HOME. Versuchen Sie, eine andere Hintergrundfarbe für die Textansicht festzulegen und einen anderen Text anzuzeigen und zu sehen, was passiert. – ams73

+0

Jedes Fragment hat seine eigene layout.xml (Jedes mit seinem eigenen TextView mit different TEXT) - Aber wie Sie sagten, es zeigt immer JUST "HOME" Es muss etwas falsch sein, aber ich kann nicht herausfinden, was – Jonas

Verwandte Themen