2012-12-29 115 views
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> 

线性布局默认占据整个屏幕宽度。

enter image description here

我想改变它programatically.I想让这样的事情:

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

请建议的方式来做到这一点。

回答

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> 

你线性布局和在列表视图FILL_PARENT在做WRAP_CONTENT,因此LinearLayout中被包装的列表视图,即全屏显示。

+0

硬编码布局宽度后,我得到了不同的东西,看我编辑的问题。我也想根据偏好改变菜单的宽度,所以我必须以编程方式做。 – vishesh

+0

将您的线性布局背景颜色更改为白色 –

+0

已更新我的答案 –

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> 

我只是直勾勾的权重。调整它们到你需要的宽度。如果你这样做,那么你不必为每个屏幕尺寸硬编码大小。