改变android中线性布局的宽度

时间:2012-12-29 04:29:16

标签: 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>

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

enter image description here

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

enter image description here

但是当我更改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>

我明白了:

enter image description here

请建议一种方法。

2 个答案:

答案 0 :(得分:4)

在listview中进行更改,如下所示,为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>

你在 Wrap_content in linear layout listview fill_parent 中,因此linearlayout包装listview即全屏。

答案 1 :(得分: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>

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

相关问题