动态设置ListView的宽度…
mDrawerLayout = (DrawerLayout) view.findViewById(R.id.drawer_layout); mDrawerList = (ListView) view.findViewById(R.id.top_sectionlist); int width = getResources().getDisplayMetrics().widthPixels/2; DrawerLayout.LayoutParams params = (android.support.v4.widget.DrawerLayout.LayoutParams) mDrawerList.getLayoutParams(); params.width = width; mDrawerList.setLayoutParams(params);
您必须手动计算屏幕大小并在运行时将动态宽度设置为抽屉布局,以下是如何在运行时获取设备屏幕宽度和高度
使用此代码,您可以获得运行时显示的宽度和高度
DisplayMetrics displaymetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displaymetrics); int height = displaymetrics.heightPixels; int width = displaymetrics.widthPixels;
现在,您需要将宽度除以2
int newWidth=width/2;
现在将宽度设置为ListView,就像这样
drawer_list.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,newWidth));
这适用于所有设备,并且将在所有设备上提供统一的大小。
这是我的解决方案,其他人需要几个百分比来显示导航抽屉。
在这里,我使用右侧导航抽屉,当抽屉向左移动时,我显示15%的主屏幕。
// convert your offset percent (here 15% ) into decimal by dividing 100 float offset = .15f * getResources().getDisplayMetrics().widthPixels ; float width = getResources().getDisplayMetrics().widthPixels - offset; DrawerLayout.LayoutParams params = (android.support.v4.widget.DrawerLayout.LayoutParams) rightNavigationView.getLayoutParams(); params.width = (int) width; rightNavigationView.setLayoutParams(params);
使用新的Android支持设计库,您可以使用android.support.percent.PercentRelativeLayout轻松完成此操作。 这是我的解决方案。
如果你问为什么在DrawerLayout和内容中有一个android:layout_marginRight="-64dp"和android:layout_marginRight="-64dp" 。 这是因为64 dp的固定边距直接编码到DrawerLayout ,不允许你使用抽屉的全部宽度。 更多关于这一点
int currentVerion = Build.VERSION.SDK_INT; int width= 0; Display display = getWindowManager().getDefaultDisplay(); Point size = new Point(); if(currentVerion >= Build.VERSION_CODES.BASE) { display.getSize(size); width = size.x; } else { width = display.getWidth(); } ((ListView) view.findViewById(R.id.top_sectionlist)).getLayoutParams().width =width/2;