DrawerLayout全屏滑动
注:DrawerLayout自带的滑动范围默认只有20dp
下面方法通过反射机制解决了此问题
1 /** 2 * 抽屉滑动范围控制 3 * @param activity 4 * @param drawerLayout 5 * @param displayWidthPercentage 占全屏的份额0~1 6 */ 7 private void setDrawerLeftEdgeSize(Activity activity, DrawerLayout drawerLayout, float displayWidthPercentage) { 8 if (activity == null || drawerLayout == null) 9 return; 10 try { 11 // find ViewDragHelper and set it accessible 12 Field leftDraggerField = drawerLayout.getClass().getDeclaredField("mLeftDragger"); 14 leftDraggerField.setAccessible(true); 15 ViewDragHelper leftDragger = (ViewDragHelper) leftDraggerField.get(drawerLayout); 16 // find edgesize and set is accessible 17 Field edgeSizeField = leftDragger.getClass().getDeclaredField("mEdgeSize"); 18 edgeSizeField.setAccessible(true); 19 int edgeSize = edgeSizeField.getInt(leftDragger); 20 // set new edgesize 21 // Point displaySize = new Point(); 22 DisplayMetrics dm = new DisplayMetrics(); 23 activity.getWindowManager().getDefaultDisplay().getMetrics(dm); 24 edgeSizeField.setInt(leftDragger, Math.max(edgeSize, (int) (dm.widthPixels * displayWidthPercentage))); 25 } catch (NoSuchFieldException e) { 26 Log.e("NoSuchFieldException", e.getMessage().toString()); 27 } catch (IllegalArgumentException e) { 28 Log.e("IllegalArgumentException", e.getMessage().toString()); 29 } catch (IllegalAccessException e) { 30 Log.e("IllegalAccessException", e.getMessage().toString()); 31 } 32 }
使用时只要调用此方法就行
1 setDrawerLeftEdgeSize(this, mDrawerLayout, 0.6f);
===========================================分割线====================================
当使用的DrawerLayout是自定义控件时出现的问题
1 Field leftDraggerField = drawerLayout.getClass().getDeclaredField("mLeftDragger");
这里会抛出NoSuchFieldException异常,原因是mLeftDragger变量是在DrawerLayout类里面定义的,在自定义的类中并没有定义。
解决方法:改为获取自定义类的父类也即DrawerLayout类中的mLeftDragger即可,替换如下
1 Field leftDraggerField = getDeclaredField(drawerLayout, "mLeftDragger");
1 /** 2 * 循环向上转型, 获取对象的 DeclaredField 3 * 4 * @param object : 子类对象 5 * @param fieldName : 父类中的属性名 6 * @return 父类中的属性对象 7 */ 8 public Field getDeclaredField(Object object, String fieldName) { 9 Field field = null; 10 11 Class<?> clazz = object.getClass(); 12 13 for (; clazz != Object.class; clazz = clazz.getSuperclass()) { 14 try { 15 field = clazz.getDeclaredField(fieldName); 16 return field; 17 } catch (Exception e) { 18 //这里甚么都不要做!并且这里的异常必须这样写,不能抛出去。 19 //如果这里的异常打印或者往外抛,则就不会执行clazz = clazz.getSuperclass(),最后就不会进入到父类中了 20 } 21 } 22 23 return null; 24 }