2017-01-18 3 views
0

Я делаю навигацию Ящик, я добавил все файлы и добавил библиотеки для того же .. я скопировал этот навигационный ящик из примера .. и он работал нормально .. но когда я попробовал это в своем проекте ..its не появляется. Но его показывая FragmentOne, который должен быть открыт, когда первый пункт нажмите (. Это означает, что на позиции 0)Навигационный ящик не работает в android?

вот мой actvitity, где я хочу, чтобы показать панель навигации

PMCompaniesActivity:

public class PMCompaniesActivity extends AppCompatActivity 
      implements NavigationView.OnNavigationItemSelectedListener { 

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



      DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
      ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
        this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); 
      drawer.setDrawerListener(toggle); 
      toggle.syncState(); 

      NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); 
      navigationView.setNavigationItemSelectedListener(this); 

      //add this line to display menu1 when the activity is loaded 
      displaySelectedScreen(0); 
     } 


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

     @Override 
     public boolean onCreateOptionsMenu(Menu menu) { 
      // Inflate the menu; this adds items to the action bar if it is present. 
      getMenuInflater().inflate(R.menu.menu_main 
        , menu); 
      return true; 
     } 

     @Override 
     public boolean onOptionsItemSelected(MenuItem item) { 
      switch (item.getItemId()) { 
       case R.id.action_settings: 
        // User chose the "Settings" item, show the app settings UI... 


       // case R.id.action_cart: 


        //Intent ibs = new Intent(MainActivity.this,AddToCart.class); 
        //ibs.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
        // startActivity(ibs); 
        // finish(); 
        break; 
       // User chose the "Favorite" action, mark the current item 
       // as a favorite... 


       default: 
        // If we got here, the user's action was not recognized. 
        // Invoke the superclass to handle it. 
        return super.onOptionsItemSelected(item); 

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

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

       displaySelectedScreen(0); 
      } 
      else if (id == R.id.pgnsrch) 
      { 
       displaySelectedScreen(1); 
      } 
      else if (id == R.id.Fanciers1) 
      { 
       displaySelectedScreen(2); 
      } else if (id == R.id.company1) 

      { 
       displaySelectedScreen(3); 
      } 
      else if (id == R.id.Article1) 
      { 
       displaySelectedScreen(4); 
      } else if (id == R.id.Settings1) 
      { 
       displaySelectedScreen(5); 
      } 
      return true; 
     } 

    private void displaySelectedScreen(int position) 
    { 
     try { 

      Fragment fragment = null; 

      if (position == 0) 
      { 
       fragment = new FragmentOne(); 
      } 
      else if (position == 1) 
      { 

      } 
      else if (position == 2) 
      { 

      } else if (position == 3) { 

      } else if (position == 4) { 

      } else if (position == 5) { 

      } 

      //replacing the fragment 
      if (fragment != null) { 
       FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); 
       ft.replace(R.id.content_frame, fragment); 
       ft.commit(); 
      } 

      DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
      drawer.closeDrawer(GravityCompat.START); 
     }catch (Exception e){ 
      e.printStackTrace(); 
     } 
    } 
} 

здесь activity_pmcompanies.xml:

<?xml version="1.0" encoding="utf-8"?> 
<android.support.v4.widget.DrawerLayout 
    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:id="@+id/drawer_layout" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:fitsSystemWindows="true" 
    tools:openDrawer="start"> 
    <include 
     layout="@layout/app_bar_main" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 

    <android.support.design.widget.NavigationView 
     android:id="@+id/nav_view" 
     android:layout_width="wrap_content" 
     android:layout_height="match_parent" 
     android:layout_gravity="start" 
     android:fitsSystemWindows="true" 

     app:headerLayout="@layout/nav_header_main" 
     app:menu="@menu/activity_main_drawer" /> 



</android.support.v4.widget.DrawerLayout> 

вот мой app_bar_main:

<?xml version="1.0" encoding="utf-8"?> 
<android.support.design.widget.CoordinatorLayout 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" 
    android:fitsSystemWindows="true" 
    tools:context="com.pigeonmarket.PMSettingsActivity" > 

    <android.support.design.widget.AppBarLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:theme="@style/AppTheme.AppBarOverlay"> 

     <android.support.v7.widget.Toolbar 
      android:id="@+id/toolbar" 
      android:layout_width="match_parent" 
      android:layout_height="?attr/actionBarSize" 
      android:background="?attr/colorPrimary" 
      app:popupTheme="@style/AppTheme.PopupOverlay" /> 

    </android.support.design.widget.AppBarLayout> 

    <include 
     layout="@layout/content_main2" 
     /> 
</android.support.design.widget.CoordinatorLayout> 

и вот contain_main2.xml:

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

<FrameLayout 
    android:layout_marginTop="?actionBarSize" 
    android:id="@+id/content_frame" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

</FrameLayout> 
</RelativeLayout> 

Его не показывает мне какую-либо ошибку на LogCat ..

+0

У вас есть два 'DrawerLayout', оба с одинаковым ID, один вложенный внутри другого. Избавьтесь от 'DrawerLayout' в' app_bar_main'. Я также хотел бы указать, что у вас нет 'ViewGroup' с идентификатором' content_frame' в любом из размещенных макетов, поэтому я не совсем уверен, как работает ваш «FragmentTransaction». –

+0

Извините, я не получаю вас ... в панели приложений, где id ur говорит abt? Я опубликую другие файлы, где вы можете увидеть содержимое _frame –

+0

Избавьтесь от '' и его соответствующего '' в макете 'app_bar_main'. Вам нужна только одна установка DrawerLayout, и вы получили ее в 'activity_pmcompanies'. –

ответ

0

Вы можете разместить код для вас OnCreate() метод? Может быть, там чего-то не хватает.

Взгляните на статьи, которые я разместил здесь. Я надеюсь, они могут вам помочь: https://stackoverflow.com/a/42253634/7013753

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