У меня был ящик для навигации, работающий некоторое время назад, но затем я решил обновить его, чтобы использовать Toolbar
вместо панели действий по умолчанию. Теперь у меня есть ситуация, когда я нажимаю меню гамбургера, навигационный ящик не открывается. Тем не менее, я могу скользить слева направо и открывать его. Проблема в том, что теперь она пуста.Ящик навигации на леденец пуст после добавления панели инструментов
значения-V21/styles.xml
<style name="Material" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/app_green</item>
<item name="colorPrimaryDark">@color/app_green_dark</item>
<item name="android:textColorPrimary">@color/action_bar_text</item>
<item name="android:textColor">@color/secondary_text_color</item>
<item name="android:color">@color/secondary_text_color</item>
<item name="android:colorAccent">@color/app_green</item>
<item name="android:editTextColor">@color/secondary_text_color</item>
<item name="textHeaderMaxLines">@integer/text_header_max_lines</item>
<item name="trackAbstractMaxLines">@integer/track_abstract_max_lines</item>
<item name="activatableItemBackground">@drawable/activatable_item_background</item>
<!-- ActionBar Styles -->
<item name="android:windowNoTitle">true</item>
<!--We will be using the toolbar so no need to show ActionBar-->
<item name="android:windowActionBar">false</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">?android:attr/colorPrimaryDark</item>
<!-- Global UI Assignments -->
<item name="android:spinnerStyle">@style/Material.Widget.Spinner</item>
<item name="android:buttonStyle">@style/Material.Widget.Button</item>
<item name="android:checkboxStyle">@style/Material.Widget.Checkbox</item>
<item name="android:textAppearance">@android:style/TextAppearance</item>
<item name="android:popupWindowStyle">@style/Material.Window.Popup</item>
<!-- ViewPager -->
<item name="vpiCirclePageIndicatorStyle">@style/Material.Activity.Login.ViewPagerIndicator.CustomCircle</item>
<item name="buttonBarStyle">?android:buttonBarStyle</item>
<item name="buttonBarButtonStyle">?android:buttonBarButtonStyle</item>
<item name="indeterminateProgressStyle">?android:indeterminateProgressStyle</item>
</style>
navigation_drawer.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<!-- The main content view. Must be first child because XML ordering implies stacking
context -->
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical">
<!-- Our App Bar. Placed here so we can draw over it with the navigation drawer. -->
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?android:attr/actionBarSize"
android:background="?android:attr/colorPrimary" />
<!-- Our actual content view. -->
<FrameLayout
android:id="@+id/drawer_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" />
</LinearLayout>
<!-- The navigation drawer itself. -->
<ListView
android:id="@+id/drawer_list"
android:layout_width="300dp"
android:layout_height="match_parent"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:layout_gravity="start"
android:background="@android:color/white"
android:fitsSystemWindows="true"
/>
NavigationDr awerActivity.java
public class NavigationDrawerActivity extends ActionBarActivity
implements AdapterView.OnItemClickListener {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private LayoutInflater mInflater;
private NavDrawerItemAdapter mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
// Our "App bar". This will only be populated if the current SDK is >= 21. Otherwise, we'll use an
// action bar that will be populated when the app first starts.
private Toolbar mAppBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_drawer);
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
setupNavigationDrawer();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Pass the event to ActionBarDrawerToggle, if it returns
// true, then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Toggles the state of the navigation drawer (i.e. closes it if it's open, and opens it if
* it's closed).
*/
public void toggleNavigationDrawer() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
closeNavigationDrawer();
} else {
openNavigationDrawer();
}
}
/**
* Opens the navigation drawer.
*/
public void openNavigationDrawer() {
mDrawerLayout.openDrawer(GravityCompat.START);
}
/**
* Closes the navigation drawer.
*/
public void closeNavigationDrawer() {
mDrawerLayout.closeDrawer(GravityCompat.START);
}
/**
* Initializes items specific to the navigation drawer.
*/
private void setupNavigationDrawer() {
mDrawerLayout = (DrawerLayout) mInflater.inflate(R.layout.navigation_drawer, null); // "null" is important.
mDrawerLayout.setStatusBarBackgroundColor(getResources().getColor(R.color.app_green));
// We want to use the toolbar if the version is 21 or greater, because is has more flexibility
// than the standard ActionBar
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mAppBar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(mAppBar);
}
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayShowHomeEnabled(false);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* Our context (Activity that hosts this drawer) */
mDrawerLayout, /* The DrawerLayout where the nav drawer will be drawn */
mAppBar, /* The Toolbar that is being used as an app bar. */
R.string.drawer_open, /* Description of "open drawer", for accessibility */
R.string.drawer_close /* Description of "close drawer", for accessibility */
) {
/**
* Called when a drawer has settled in a completely closed state.
*/
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
supportInvalidateOptionsMenu();
}
/**
* Called when a drawer has settled in a completely open state.
*/
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
supportInvalidateOptionsMenu();
}
};
mDrawerList = (ListView) mDrawerLayout.findViewById(R.id.drawer_list);
NavDrawerGroup userToolsGroup = new NavDrawerGroup(R.string.drawer_group_usertools, false, 1);
NavDrawerGroup toolBoxGroup = new NavDrawerGroup(R.string.drawer_group_toolbox, true, 2);
NavDrawerGroup supportGroup = new NavDrawerGroup(R.string.drawer_group_support, true, 3);
NavDrawerItem[] navDrawerItems = {
new NavDrawerItem(R.string.drawer_item_main, R.drawable.ic_main, NavDrawerGroup.DEFAULT_GROUP),
new NavDrawerItem(R.string.drawer_item_tool_one, R.drawable.ic_tool_one, NavDrawerGroup.DEFAULT_GROUP),
new NavDrawerItem(R.string.drawer_item_tool_two, R.drawable.ic_tool_two, userToolsGroup),
};
mAdapter = new NavDrawerItemAdapter(this, navDrawerItems);
mDrawerList.setAdapter(mAdapter);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerList.setOnItemClickListener(this);
}
}
Я знаю NavDrawerItem
материал выглядит своего рода шаткий, но я проверил, что он работает со старой навигации ящика (до панели инструментов), и все это на самом деле делает это какая-то логика для заполнения ListView
элементы с иконкой и поместите их в соответствующую группу. Поэтому я уверен, что это не проблема.
Даже если бы это было, я должен был получить что-то другое, кроме пустого белого фона, потому что макет для ящика навигации фактически устанавливает заголовок для ListView
, который имеет зеленый фон, который я не вижу.
Edit:
В соответствии с @ blacksh33p Замечаний ниже, я удалил код, который обрабатывается различные уровни API по-разному, и изменил mDrawerToggle
конструктор:
Hm, ни радости. Я удалил условное определение уровня API, и только инициализирован Toolbar
, а затем изменил mDrawerToggle
на следующее:
mDrawerToggle = new ActionBarDrawerToggle(
this, /* Our context (Activity that hosts this drawer) */
mDrawerLayout, /* The DrawerLayout where the nav drawer will be drawn */
mAppBar, /* The Toolbar that is being used as an app bar. */
R.string.drawer_open, /* Description of "open drawer", for accessibility */
R.string.drawer_close /* Description of "close drawer", for accessibility */
) {
/**
* Called when a drawer has settled in a completely closed state.
*/
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
supportInvalidateOptionsMenu();
}
/**
* Called when a drawer has settled in a completely open state.
*/
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
supportInvalidateOptionsMenu();
}
};
Но, в конечном итоге с тем же результатом. :(
Кроме того, я заметил, что когда я запустить приложение в отладчике, он не ударил точки останова, установленные в 'onDrawerOpened()' или 'onDrawerClosed()', даже когда я покинул прикосновение, чтобы открыть навигационный ящик. – jwir3