2014-11-21 3 views
0

У меня есть ящик для навигации в моем приложении. Если я выбираю конкретный элемент и сдвигаю навигационный ящик. Фрагмент перекрывает ящик навигации.Мой фрагмент скрывает навигационный ящик?

Я попытался добавить popBackStackImmediate(); Но это бесполезно. Вот как это выглядит

enter image description here

активность

public class Activity extends MainActivity 
{ 

    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState); 
    } 

    @Override 
    public void onNavigationDrawerItemSelected(int position) 
    { 
     // TODO Auto-generated method stub 
     if (position == 1) 
     { 
      HomeFragment Frag = new HomeFragment(); 
      FragmentTransaction transaction = getFragmentManager().beginTransaction(); 
      transaction.replace(R.id.container, Frag); 
      transaction.commit(); 
     } 
     else if (position == 2) 
     { 

     } 
    } 
    public void onDrawerOpened(View drawerview) 
    { 
     getFragmentManager().popBackStackImmediate(); 
    } 

Navigation Fragment

public class NavigationDrawerFragment extends Fragment implements NavigationDrawerCallbacks 
{ 
    private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned"; 
    private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position"; 
    private static final String PREFERENCES_FILE = "my_app_settings"; 
    private NavigationDrawerCallbacks mCallbacks; 
    private RecyclerView mDrawerList; 
    private View mFragmentContainerView; 
    private DrawerLayout mDrawerLayout; 
    private ActionBarDrawerToggle mActionBarDrawerToggle; 
    private boolean mUserLearnedDrawer; 
    private boolean mFromSavedInstanceState; 
    private int mCurrentSelectedPosition; 

    @Nullable 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    { 
     View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false); 
     mDrawerList = (RecyclerView) view.findViewById(R.id.drawerList); 
     LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); 
     layoutManager.setOrientation(LinearLayoutManager.VERTICAL); 
     mDrawerList.setLayoutManager(layoutManager); 
     mDrawerList.setHasFixedSize(true); 

     final List<NavigationItem> navigationItems = getMenu(); 
     NavigationDrawerAdapter adapter = new NavigationDrawerAdapter(navigationItems); 
     adapter.setNavigationDrawerCallbacks(this); 
     mDrawerList.setAdapter(adapter); 
     selectItem(mCurrentSelectedPosition); 
     return view; 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     mUserLearnedDrawer = Boolean.valueOf(readSharedSetting(getActivity(), PREF_USER_LEARNED_DRAWER, "false")); 
     if (savedInstanceState != null) 
     { 
      mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION); 
      mFromSavedInstanceState = true; 
     } 
    } 

    @Override 
    public void onAttach(Activity activity) 
    { 
     super.onAttach(activity); 
     try 
     { 
      mCallbacks = (NavigationDrawerCallbacks) activity; 
     } 
     catch (ClassCastException e) 
     { 
      throw new ClassCastException("Activity must implement NavigationDrawerCallbacks."); 
     } 
    } 

    public ActionBarDrawerToggle getActionBarDrawerToggle() 
    { 
     return mActionBarDrawerToggle; 
    } 

    public void setActionBarDrawerToggle(ActionBarDrawerToggle actionBarDrawerToggle) 
    { 
     mActionBarDrawerToggle = actionBarDrawerToggle; 
    } 

    public void setup(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) 
    { 
     mFragmentContainerView = getActivity().findViewById(fragmentId); 
     mDrawerLayout = drawerLayout; 
     mActionBarDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) 
     { 
      @Override 
      public void onDrawerClosed(View drawerView) 
      { 
       super.onDrawerClosed(drawerView);    
       if (!isAdded()) 
        return; 
       getActivity().invalidateOptionsMenu(); 
      } 

      @Override 
      public void onDrawerOpened(View drawerView) 
      { 
       super.onDrawerOpened(drawerView); 
       if (!isAdded()) 
        return; 
       if (!mUserLearnedDrawer) 
       { 
        mUserLearnedDrawer = true; 
        saveSharedSetting(getActivity(), PREF_USER_LEARNED_DRAWER, "true"); 
       }    
       getActivity().invalidateOptionsMenu(); 
      } 
     }; 

     if (!mUserLearnedDrawer && !mFromSavedInstanceState) 
      mDrawerLayout.openDrawer(mFragmentContainerView); 

     mDrawerLayout.post(new Runnable() 
     { 
      @Override 
      public void run() 
      { 
       mActionBarDrawerToggle.syncState(); 
      } 
     }); 

     mDrawerLayout.setDrawerListener(mActionBarDrawerToggle); 
    } 

    public void openDrawer() 
    { 
     mDrawerLayout.openDrawer(mFragmentContainerView); 
    } 

    public void closeDrawer() 
    { 
     mDrawerLayout.closeDrawer(mFragmentContainerView); 
    } 

    @Override 
    public void onDetach() 
    { 
     super.onDetach(); 
     mCallbacks = null; 
    } 

    public List<NavigationItem> getMenu() 
    { 
     List<NavigationItem> items = new ArrayList<NavigationItem>(); 
     items.add(new NavigationItem("Home", getResources().getDrawable(R.drawable.play))); 
     items.add(new NavigationItem("News", getResources().getDrawable(R.drawable.play))); 
     items.add(new NavigationItem("Videos", getResources().getDrawable(R.drawable.play))); 
     items.add(new NavigationItem("Playlist", getResources().getDrawable(R.drawable.play))); 
     return items; 
    } 

    void selectItem(int position) 
    { 
     mCurrentSelectedPosition = position; 
     if (mDrawerLayout != null) 
     { 
      mDrawerLayout.closeDrawer(mFragmentContainerView); 
     } 
     if (mCallbacks != null) 
     { 
      mCallbacks.onNavigationDrawerItemSelected(position); 
     } 
     ((NavigationDrawerAdapter) mDrawerList.getAdapter()).selectPosition(position); 
    } 

    public boolean isDrawerOpen() 
    { 
     return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView); 
    } 

    @Override 
    public void onConfigurationChanged(Configuration newConfig) 
    { 
     super.onConfigurationChanged(newConfig); 
     mActionBarDrawerToggle.onConfigurationChanged(newConfig); 
    } 

    @Override 
    public void onSaveInstanceState(Bundle outState) 
    { 
     super.onSaveInstanceState(outState); 
     outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition); 
    } 

    @Override 
    public void onNavigationDrawerItemSelected(int position) 
    { 
     mCallbacks.onNavigationDrawerItemSelected(position); 
     selectItem(position); 

    } 

    public DrawerLayout getDrawerLayout() 
    { 
     return mDrawerLayout; 
    } 

    public void setDrawerLayout(DrawerLayout drawerLayout) 
    { 
     mDrawerLayout = drawerLayout; 
    } 
} 

Компоновка активность

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <include 
     android:id="@+id/toolbar_actionbar" 
     layout="@layout/toolbar_default" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content"/> 

    <android.support.v4.widget.DrawerLayout 
     android:id="@+id/drawer" 
     xmlns:android="http://schemas.android.com/apk/res/android" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_below="@+id/toolbar_actionbar"> 

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

     <!-- android:layout_marginTop="?android:attr/actionBarSize"--> 
     <fragment 
      android:id="@+id/fragment_drawer" 
      android:name="com.RemoteIt.client.activity.drawer.NavigationDrawerFragment" 
      android:layout_width="@dimen/navigation_drawer_width" 
      android:layout_height="match_parent" 
      android:layout_gravity="start" 
      app:layout="@layout/fragment_navigation_drawer"/> 
    </android.support.v4.widget.DrawerLayout> 
</RelativeLayout> 

HomeFragment

public class HomeFragment extends Fragment 
{ 

    public HomeFragment() 
    {} 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    {  View v = inflater.inflate(R.layout.home, container, false); 

     int redActionButtonSize = getResources().getDimensionPixelSize(R.dimen.red_action_button_size); 
     int redActionButtonMargin = getResources().getDimensionPixelOffset(R.dimen.action_button_margin); 
     int redActionButtonContentSize = getResources().getDimensionPixelSize(R.dimen.red_action_button_content_size); 
     int redActionButtonContentMargin = getResources().getDimensionPixelSize(R.dimen.red_action_button_content_margin); 
     int redActionMenuRadius = getResources().getDimensionPixelSize(R.dimen.red_action_menu_radius); 
     int blueSubActionButtonSize = getResources().getDimensionPixelSize(R.dimen.blue_sub_action_button_size); 
     int blueSubActionButtonContentMargin = getResources().getDimensionPixelSize(R.dimen.blue_sub_action_button_content_margin); 

     ImageView fabIconStar = new ImageView(getActivity()); 
     fabIconStar.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_important)); 

     FloatingActionButton.LayoutParams starParams = new FloatingActionButton.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT); 
     starParams.setMargins(redActionButtonMargin, redActionButtonMargin, redActionButtonMargin, redActionButtonMargin); 
     fabIconStar.setLayoutParams(starParams); 

     FloatingActionButton.LayoutParams fabIconStarParams = new FloatingActionButton.LayoutParams(redActionButtonContentSize, redActionButtonContentSize); 
     fabIconStarParams.setMargins(redActionButtonContentMargin, redActionButtonContentMargin, redActionButtonContentMargin, redActionButtonContentMargin); 

     FloatingActionButton leftCenterButton = new FloatingActionButton.Builder(getActivity()).setContentView(fabIconStar, fabIconStarParams).setBackgroundDrawable(R.drawable.button_action_red_selector).setPosition(FloatingActionButton.POSITION_TOP_CENTER).setLayoutParams(starParams).build(); 

     // Set up customized SubActionButtons for the right center menu 
     SubActionButton.Builder lCSubBuilder = new SubActionButton.Builder(getActivity()); 
     lCSubBuilder.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_action_blue_selector)); 

     FrameLayout.LayoutParams blueContentParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT); 
     blueContentParams.setMargins(blueSubActionButtonContentMargin, blueSubActionButtonContentMargin, blueSubActionButtonContentMargin, blueSubActionButtonContentMargin); 
     lCSubBuilder.setLayoutParams(blueContentParams); 
     // Set custom layout params 
     FrameLayout.LayoutParams blueParams = new FrameLayout.LayoutParams(blueSubActionButtonSize, blueSubActionButtonSize); 
     lCSubBuilder.setLayoutParams(blueParams); 

     ImageView lcIcon1 = new ImageView(getActivity()); 
     ImageView lcIcon2 = new ImageView(getActivity()); 
     ImageView lcIcon3 = new ImageView(getActivity()); 
     ImageView lcIcon4 = new ImageView(getActivity()); 
     ImageView lcIcon5 = new ImageView(getActivity()); 
     ImageView lcIcon6 = new ImageView(getActivity()); 
     ImageView lcIcon7 = new ImageView(getActivity()); 
     ImageView lcIcon8 = new ImageView(getActivity()); 
     ImageView lcIcon9 = new ImageView(getActivity()); 

     lcIcon1.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_camera)); 
     lcIcon2.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_picture)); 
     lcIcon3.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_video)); 
     lcIcon4.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_location_found)); 
     lcIcon5.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_headphones)); 
     lcIcon6.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_camera)); 
     lcIcon7.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_picture)); 
     lcIcon8.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_video)); 
     lcIcon9.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_location_found)); 

     // Build another menu with custom options 
     FloatingActionMenu leftCenterMenu = new FloatingActionMenu.Builder(getActivity()).addSubActionView(lCSubBuilder.setContentView(lcIcon1, blueContentParams).build()).addSubActionView(lCSubBuilder.setContentView(lcIcon2, blueContentParams).build()).addSubActionView(lCSubBuilder.setContentView(lcIcon3, blueContentParams).build()).addSubActionView(lCSubBuilder.setContentView(lcIcon4, blueContentParams).build()).addSubActionView(lCSubBuilder.setContentView(lcIcon5, blueContentParams).build()) 
       .addSubActionView(lCSubBuilder.setContentView(lcIcon6, blueContentParams).build()).addSubActionView(lCSubBuilder.setContentView(lcIcon7, blueContentParams).build()).addSubActionView(lCSubBuilder.setContentView(lcIcon8, blueContentParams).build()).addSubActionView(lCSubBuilder.setContentView(lcIcon9, blueContentParams).build()).setRadius(redActionMenuRadius).setStartAngle(0).setEndAngle(360).attachTo(leftCenterButton).build(); 

     return v; 
    } 

} 
+0

Не могли бы вы также разместить свой макет xml? –

+0

@JustinPowell См. Мое редактирование ... – AruLNadhaN

ответ

1

Следующие изменения были внесены в классы FloatingActionButton и FloatingActionMenu, чтобы можно было установить определенную группу ViewGroup в качестве контейнера для обоих. Тесты проводились с аналогичной, но более простой версией кода, который вы опубликовали, поэтому вам может потребоваться внести коррективы в параметры настройки.

В библиотечном коде предполагается, что кнопка и меню будут отображаться поверх содержимого содержимого Activity и все в нем. Добавление члена ViewGroup контейнера в классе FloatingActionButton позволяет нам вместо этого указать дочернюю группу ViewGroup. Обратите внимание, что следующие изменения будут работать, только если в меню используется FloatingActionButton.

Дополнения к FloatingActionButton класса:

public class FloatingActionButton extends FrameLayout { 
    ... 
    private ViewGroup containerView; 
    ... 
    public FloatingActionButton(Activity activity, 
           LayoutParams layoutParams, 
           int theme, 
           Drawable backgroundDrawable, 
           int position, 
           View contentView, 
           FrameLayout.LayoutParams contentParams  
           // Note the addition of the following 
           // constructor parameter here 
           , ViewGroup containerView) { 
     ... 
     setClickable(true); 

     // This line is new. The rest of the constructor is the same. 
     this.containerView = containerView;  

     attach(layoutParams); 
    } 
    ... 
    public View getActivityContentView() { 
     if(containerView == null) { 
      return ((Activity)getContext()) 
       .getWindow().getDecorView().findViewById(android.R.id.content); 
     } else { 
      return containerView; 
     } 
    } 

    public ViewGroup getContainerView() { 
     return containerView; 
    } 

    // The following setter is not strictly necessary, but may be of use 
    // if you want to toggle the Button's and Menu's z-order placement 
    public void setContainerView(ViewGroup containerView) { 
     this.containerView = containerView; 
    } 
    ... 
    public static class Builder { 
     ... 
     private ViewGroup containerView; 
     ... 
     public Builder setContainerView(ViewGroup containerView) { 
      this.containerView = containerView; 
      return this; 
     } 

     public FloatingActionButton build() { 
      return new FloatingActionButton(activity, 
              layoutParams, 
              theme, 
              backgroundDrawable, 
              position, 
              contentView, 
              contentParams, 
              // New argument 
              containerView); 
     } 
    } 
    ... 
} 

И изменения к FloatingActionMenu класса:

public class FloatingActionMenu { 
    ... 
    public View getActivityContentView() { 
     if(mainActionView instanceof FloatingActionButton && 
      ((FloatingActionButton) mainActionView).getContainerView() != null) { 
      return ((FloatingActionButton) mainActionView).getContainerView(); 
     } else { 
      return ((Activity)mainActionView.getContext()) 
       .getWindow().getDecorView().findViewById(android.R.id.content); 
     } 
    } 
    ... 
} 

Затем в onCreateView() методе фрагмента, нам нужно добавить вызов новый setContainerView() метод класса FloatingActionButton.Builder.

public class HomeFragment extends Fragment { 
    ... 
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) 
    { 
     ... 
     FloatingActionButton leftCenterButton = new FloatingActionButton.Builder(getActivity()) 
      .setContentView(fabIconStar, null) 
      .setBackgroundDrawable(R.drawable.ic_launcher) 
      .setPosition(FloatingActionButton.POSITION_TOP_CENTER) 
      .setLayoutParams(starParams) 
      // The new method call is added here 
      .setContainerView(container) 
      .build(); 
     ... 
    } 
    ... 
} 
+0

Я забыл упомянуть, что вы все еще можете использовать модифицированную библиотеку, как первоначально предполагалось, т. Е. Z-упорядоченную над всей Activity, просто опуская вызов 'setContainerView()' на 'Builder'. –

+0

Он работает для ящика. Но когда я перехожу из фрагмента А в фрагмент Б. Нельзя заменить плавающий аэродром? – AruLNadhaN

+0

Я не уверен, что вы имеете в виду. Что не меняется? Изображения? Просто кнопка, или все меню? У каждого фрагмента есть другая кнопка и меню? Есть ли у HomeFragment кнопка/Меню, которая должна исчезнуть, когда вы переключаетесь на другой фрагмент? Вы уверены, что второй Фрагмент загружается правильно? –

0

Пожалуйста, замените строку ниже кода

transaction.replace(R.id.container, Frag); 

с

transaction.replace(R.id.content_frame, Frag); 

Я имел эту проблему раз перекрывающийся за счет в ndroid.R.id.content и я заменил его R.id.content_frame, который решил мою проблему.

Но я вижу в вашем коде, что вы использовали другой идентификатор вида контейнера, но это должно работать.

+0

Нет идентификатора, называемого R.id.content? – AruLNadhaN

+0

Это «android.R.id.content», а не «R.id.content». Также вы должны использовать «R.id.content_frame», как указано выше. –

+0

Я пробовал Оба. Он не найден! – AruLNadhaN

Смежные вопросы