1

В настоящее время я перепроектирую свое приложение, чтобы включить навигационный ящик для навигации по приложению. В настоящее время каждый экран - это активность и способ, которым я создал домашний экран, состоит в том, что он содержит панель инструментов и другой файл xml.Реализация навигационного ящика в действии с фрагментами

<?xml version="1.0" encoding="utf-8"?> 

<Toolbar 
    android:layout_width="match_parent" 
    android:id="@+id/toolbar" 
    android:layout_height="?attr/actionBarSize" 
    app:popupTheme="@style/AppTheme.PopupOverlay"> 
    <ImageView 
     android:layout_width="@dimen/_30sdp" 
     android:layout_height="wrap_content" 
     android:layout_marginStart="@dimen/_95sdp" 
     android:src="@drawable/logo" 
     android:id="@+id/logo" 
     /> 
    <ImageView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:src="@drawable/sync_green" 
     android:id="@+id/sync_button" 
     android:layout_marginStart="@dimen/_75sdp"/> 
</Toolbar> 
<include layout="@layout/activity_main" /> 

<android.support.design.widget.FloatingActionButton 
    android:id="@+id/fab" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_gravity="bottom|end" 
    android:layout_margin="@dimen/fab_margin" 
    android:src="@drawable/run" 
    /> 

Теперь, я сделал еще один файл XML для панели навигации:

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:app="http://schemas.android.com/apk/res-auto" 
android:id="@+id/drawer_layout" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
> 
<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical"> 

    <!-- The main content view where fragments are loaded --> 
    <FrameLayout 
     android:id="@+id/flContent" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     /> 
</LinearLayout> 

<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:menu="@menu/activity_main_drawer" /> 

Мой dilemna является то, что, так как моя панель инструментов в home.xml фрагмент, когда я переключаю фрагменты, я потеряю панель инструментов. Я хочу сохранить панель инструментов для всех видов в навигационном ящике.

Кроме того, в моем java-коде setActionBar (панель инструментов) выдает сообщение об ошибке, не могу разрешить метод setActionBar.

ответ

0

Попробуйте это в вашей деятельности

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     toolbar.setTitle(""); 
     setSupportActionBar(toolbar); 

Это мой 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" 
    android:paddingBottom="@dimen/design_navigation_separator_vertical_padding" 
    tools:openDrawer="start"> 

    <RelativeLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:background="@color/white" 
     android:orientation="vertical"> 

     <include 
      android:id="@+id/toolbar" 
      layout="@layout/apptoolbar" /> 

     <FrameLayout 
      android:id="@+id/frame_container" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      android:layout_below="@+id/nav_toolbar" 
      android:clickable="true"> 

     </FrameLayout> 
    </RelativeLayout> 

    <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:background="@color/appColor" 
     android:fitsSystemWindows="true" 
     android:paddingBottom="@dimen/design_navigation_separator_vertical_padding" 
     app:itemTextAppearance="@style/NavigationDrawerStyle" 
     app:headerLayout="@layout/nav_header_home" 
     app:itemBackground="@color/appColor" 
     app:itemTextColor="@color/drawable_selector_drawer_item" 
     app:menu="@menu/activity_home_drawer" /> 

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

Итак, я должен поместить свою панель инструментов в базовую операцию? Как насчет XML? Могу ли я поставить его вместе с drawerlayout? И я не могу использовать supportActionBar, я не использую библиотеку поддержки для этой панели инструментов. –

+0

проверьте выше код и расположение –

1

Один простой и straightforwrd решение для интеграции NavigationDrawer вместе с фрагментом в деятельности, заключается в разработке activity_main.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" 
    android:layoutDirection="rtl" 
    tools:openDrawer="start"> 

    <include 
     layout="@layout/content_act_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" 
     android:background="@color/flat_white_light"> 

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

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

Теперь в content_act_main.xml вы можете иметь:

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

    <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="?actionBarSize" 
      android:background="?attr/colorPrimary" 
      android:theme="@style/ToolbarColoredBackArrow" 
      app:popupTheme="@style/AppTheme.PopupOverlay" > 

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

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

    <FrameLayout 
     android:id="@+id/fragment_container" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     app:layout_behavior="@string/appbar_scrolling_view_behavior" /> 

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

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

+0

Спасибо, это помогает. Я попробую и дам вам знать. –

+0

Это работает, за исключением того, что мой макет ужасно испорчен. Какие-либо предложения? Http: // TinyPic.com/r/2rwkinc/9 –

+0

Показать xml макета на картинке –

1

Вы, конечно, можете сохранить эту панель инструментов, необходимо ActionBarDrawerToggle связать drawerLayout и Toolbar вместе.

Минимальная конфигурация будет более или менее:

ActionBarDrawerToggle actionBarDrawerToggle; 
    DrawerLayout drawerLayout; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     drawerLayout = (DrawerLayout) findViewById(R.id.navigation_drawer); 
     setSupportActionBar(toolbar); 

     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
     getSupportActionBar().setHomeButtonEnabled(true); 
     actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.app_name,R.string.app_name); 
     drawerLayout.setDrawerListener(actionBarDrawerToggle); 
    } 

И вы положили панель инструментов в макете базовой деятельности и других видах завернутый в DrawerLayout.

<Android.support.v4.widget.DrawerLayout 
     xmlns:Android="http://schemas.Android.com/apk/res/Android" 
     Android:id="@+id/navigation_drawer" 
     Android:layout_width="match_parent" 
     Android:layout_height="match_parent" 
     Android:fitsSystemWindows="true"> 

     <Android.support.v7.widget.Toolbar 
      xmlns:Android="http://schemas.Android.com/apk/res/Android" 
      xmlns:app="http://schemas.Android.com/apk/res-auto" 
      Android:id="@+id/toolbar" 
      Android:layout_width="match_parent" 
      Android:layout_height="wrap_content" 
      ></Android.support.v7.widget.Toolbar> 
     .... 
     .... 
    </Android.support.v4.widget.DrawerLayout> 
+0

Не в состоянии. setSupportActionbar не разрешен. И если я не использую библиотеку поддержки, функция ActionBarDrawerToggle() не принимает правильные параметры. –

+0

Я. В большинстве случаев * setSupportActionbar * распознается под 'android.support.v7.widget.Toolbar' и расширяется' AppCompatActivity' или 'ActionBarActivity'. –

+0

Не в состоянии. setSupportActionbar не разрешен. И если я не использую библиотеку поддержки, функция ActionBarDrawerToggle() не принимает правильные параметры. Я передал конструктор без параметра «toolbar», и мой экран теперь перекошен. http://tinypic.com/r/2nki6pd/9 –

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