5

我有一个列表视图的这个 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>

线性布局默认占据全屏宽度。

在此处输入图像描述

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

在此处输入图像描述

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

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

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

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

</ListView>

我明白了:

在此处输入图像描述

请提出一种方法来做到这一点。

4

2 回答 2

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>

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

于 2012-12-29T04:37:25.150 回答
2

如果您希望它适合多种屏幕尺寸,我建议添加一个空布局并使用权重。

像这样:

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


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

</ListView>

<LinearLayout android:layout_width="0dp"
android:layout_height="fill_parent" 
android:layout_weight="1"
android:orientation="horizontal" android:background="@android:color/white">

</LinearLayout>

我只是盯着重量。将它们调整到您需要的宽度。如果您这样做,那么您将不必为每个屏幕尺寸硬编码尺寸。

于 2012-12-29T06:49:50.497 回答