改变android中线性布局的宽度

vis*_*esh 5 android android-layout

我有一个列表视图的xml布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/menu"
android:orientation="vertical" android:background="#2f4f4f" android:layout_width="wrap_content" android:layout_height="fill_parent">

  <ListView android:id="@+id/list" android:layout_width="fill_parent" android:layout_height="wrap_content"
    android:background="#2f4f4f" android:cacheColorHint="#2f4f4f" android:scrollbars="none">
  </ListView>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

默认情况下,线性布局占据整个屏幕宽度.

在此输入图像描述

我想以编程方式更改它.我想做这样的事情:

在此输入图像描述

但是当我改变线性布局的宽度时,没有任何反应,它仍占据全屏宽度

 LayoutInflater inflater = LayoutInflater.from(this);
 View menu = inflater.inflate(R.layout.xml_layout, null);
 menu.setLayoutParams(new LayoutParams(20,LayoutParams.WRAP_CONTENT));
Run Code Online (Sandbox Code Playgroud)

在列表视图中硬编码布局宽度后:

 <ListView
  android:id="@+id/list"
  android:layout_width="200dp"
  android:layout_height="wrap_content"
  android:background="#2f4f4f"
  android:cacheColorHint="#2f4f4f"
  android:scrollbars="none" >

</ListView>
Run Code Online (Sandbox Code Playgroud)

我明白了:

在此输入图像描述

请建议一种方法来做到这一点.

Rah*_*dia 4

在列表视图中进行如下所示的更改,在 XML 中对布局宽度进行硬编码。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent"
android:layout_height="fill_parent" 
android:orientation="vertical" android:background="@android:color/white">


<ListView
    android:id="@+id/list"
    android:layout_width="200dp"
    android:layout_height="wrap_content"
    android:background="#2f4f4f"   >

</ListView>

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

您正在线性布局listview fill_parent中执行 Wrap_content ,因此 Linearlayout 正在包装 listview 即全屏。