在片段中,我以编程方式将片段添加到导航抽屉中,然后从右侧打开抽屉。请注意,我无法直接访问DrawerLayout的xml文件,因此需要编程解决方案。抽屉从右侧打开并正确关闭,我保留了抽屉的打开/关闭状态,并根据状态对该配置进行了更改。
问题在于,即使更改了基于saveInstanceState布尔值的打开/关闭状态,配置更改时抽屉也会关闭(我可以看到抽屉处于关闭状态)。我在closeDrawer
中的所有DrawerLayout.class
方法中都放置了调试器,但是没有被使用。
更新:我想我知道问题出在哪里,但是我不确定如何在不扩展DrawerLayout本身的情况下解决该问题。在我的情况下,在DrawerLayout#findDrawerWithGravity
中调用的DrawerLayout#onRestoreInstanceState
返回null。
@Override
public void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putBoolean(STATE_DRAWER_OPEN,
getDrawerLayout() == null ? false : getDrawerLayout().isDrawerOpen(Gravity.RIGHT));
}
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null)
isDrawerOpen = savedInstanceState.getBoolean(STATE_DRAWER_OPEN);
}
private void setDrawer() //this is called in onCreate
{
DrawerLayout drawer = getActivity().findViewById(R.id.drawer_layout);
if (drawer == null)
drawer = getDrawerLayout();
View existing = drawer.findViewById(R.id.m_drawer_container);
if (existing != null)
drawer.removeView(existing);
drawer.setFocusableInTouchMode(false);
drawer.addDrawerListener(this);
FrameLayout fragmentContainer = new FrameLayout(getActivity());
fragmentContainer.setId(R.id.m_drawer_container);
final DrawerLayout.LayoutParams layoutParams = new DrawerLayout.LayoutParams(
getResources().getDimensionPixelSize(R.dimen.m_drawer_max_width),
ViewGroup.LayoutParams.MATCH_PARENT, Gravity.RIGHT);
drawer.addView(fragmentContainer, layoutParams);
FragmentManager fragmentManager = getFragmentManager();
MyDrawerFragment mDrawerFragment = null;
Fragment frag = fragmentManager.findFragmentByTag(TAG_DRAWER_FRAGMENT);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (frag != null && frag.isAdded())
fragmentTransaction.remove(frag);
mDrawerFragment = MyDrawerFragment.newInstance(myArgs);
fragmentTransaction.add(R.id.m_drawer_container, drawerFragment, TAG_DRAWER_FRAGMENT);
fragmentTransaction.commitAllowingStateLoss();
if (isDrawerOpen)
drawer.openDrawer(Gravity.RIGHT);
}
答案 0 :(得分:1)
结果是,从配置更改还原时,答案是调用drawer.openDrawer(Gravity.RIGHT, false);
以禁用动画。原因是调用drawer.openDrawer(Gravity.RIGHT)
的动画默认情况下设置为true,而深入研究该方法最终会导致DrawerLayout.java
中的此代码块,从而导致宽度计算不正确,从而导致抽屉为“隐藏”:
DrawerLayout.java
else if (animate) {
lp.openState |= LayoutParams.FLAG_IS_OPENING;
if (checkDrawerViewAbsoluteGravity(drawerView, Gravity.LEFT)) {
mLeftDragger.smoothSlideViewTo(drawerView, 0, drawerView.getTop());
} else {
mRightDragger.smoothSlideViewTo(drawerView, getWidth() - drawerView.getWidth(),
drawerView.getTop());
}
解决方案是从配置更改还原时将动画设置为false。
if (isDrawerOpen && isRestoreFromConfigChange)
drawer.openDrawer(Gravity.RIGHT, false);