2017-12-15 2 views
0

とフラグメントに断片は機能しません。ナビゲート</p> <p>すべてがこれまでに素晴らしい取り組んでいるが、私の唯一の問題は、ナビゲーションの間ということです私は新しいAndroid Studioプロジェクトを作成していると私は(<a href="https://github.com/mikepenz/MaterialDrawer" rel="nofollow noreferrer">Mike Penz</a>)によってGithubのプロジェクトに基づいてナビゲーションドロワーをinplementedいるMaterialDrawer

引き出しのすべてのアイテムに別のフラグメントを開きたいとします。

これはこれはこれはこれは私のfragment_home.xml

である私の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; 
    } 

} 

である私のactivity_main.xml

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

である私の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]").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(); 
     } 
    } 

} 

です

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

答えて

0

あなたのXLMアクティビティレイアウトには、フラグメントを追加して置き換えるためのフレームレイアウトスロットが最初にあります。

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

呼び出し、このようなwithOnDrawerItemClickListenerからこの方法:

が作成し、あなたの引き出しから選択したアイテムのIDに基づいて、活動にご断片を追加する責任を負うことになります。この新しいメソッドを追加します
  .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; 
       } 
      }) 

これは要件をシミュレートすることはできませんが、ロジック、幸運を提供します。

)(あなたの助けを

.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

感謝を.withIdentifierを追加 - 私はまだ私は(activity_main.xml)にでframeLayoutを追加したいくつかの助け を必要とするが、それはされていないため、問題がまだありますフラグメントを切り替える コードを – Jonas

+0

より上に更新しました。フラグメントが表示されていないことをどのように知っていましたか?これは、それぞれのフラグメントに異なる背景色や異なるテキストが含まれていないか、追加したテキストビューに別のテキストが表示されている場合を除いて、明らかではない場合があります。テキストビューに異なる背景色を設定し、別のテキストを表示して何が起こるかを見てください。 – ams73

+0

各フラグメントには独自のlayout.xmlがあります(それぞれ独自のTextViewとdiffirent TEXTがあります)。 - あなたが言ったように、それは常に "HOME"を表示します。 何かが間違っている必要がありますが、私は – Jonas

関連する問題

 関連する問題