簡體   English   中英

改變android中線性布局的寬度

[英]change the width of linear layout in android

我有一個列表視圖的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>

默認情況下,線性布局占據整個屏幕寬度。

在此輸入圖像描述

我想以編程方式更改它。我想做這樣的事情:

在此輸入圖像描述

但是當我改變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>

我明白了:

在此輸入圖像描述

請建議一種方法來做到這一點。

在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>

在線性布局listview fill_parent中做Wrap_content ,因此linearlayout包裝listview即全屏。

如果您希望它適合多種屏幕尺寸,我建議添加一個空布局並使用權重。

像這樣:

<?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>

我只是看了重量。 將它們調整到您需要的寬度。 如果你這樣做,那么你就不必為每個屏幕尺寸硬編碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM