按重量更改Android中抽屉的宽度?

我有这个设计,里面有一个抽屉:

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".Main" />

    <LinearLayout
        android:id="@+id/drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:orientation="vertical"/>

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

我想通过设置权重来改变抽屉的宽度,这个例子怎么做?我希望抽屉的宽度总是占可见屏幕宽度的1/2.

最佳答案 您可以在代码中以编程方式执行此操作.您将需要显示宽度和高度,然后您可以修改上面的线性布局的宽度.您可以通过以下方式获得高度和宽度:

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
displayViewWidth_ = size.x;
displayViewHeight_ = size.y;

然后,您可以根据此计算在代码中为布局指定新的宽度,例如:

ViewGroup.LayoutParams params = drawer.getLayoutParams()
params.width = displayViewWidth_ / 2;
drawer.setLayoutParams(params);
点赞