2012-08-24 58 views
1

我需要在ListView中顯示名稱:值對列表。我想將值與最長名稱寬度對齊。但是在收到數據之前,名稱的長度和數量是未知的。如何將名稱:值對對齊爲ListView項目

例如:

name1:   value1 
name111:  value2 
someOtherName: value3 
----------------------next ListView Item 
name3:   value4 
longestNameeee: value5 
----------------------next ListView Item 

現在我已經創建適配器使用的LinearLayout作爲項的佈局和我添加與名稱內LinearLayouts - 值對與weigth 0.5 - 0.5(裝置值示出的中間後佈局)。 但是如何根據最長名稱長度來設置名稱 - 值權重?

+0

如何使用雙列gridview,其中一列的所有行的寬度相同。下面是關於如何控制GridView中列寬的建議:http://stackoverflow.com/questions/985153/how-to-make-a-gridview-stretchable-in-android-to-expand-the-column-width -去任何 –

回答

1

也許你可以考慮在你的列表視圖行佈局中使用相對佈局,並將名稱與左邊的值和右邊的值對齊?

另一種選擇可能是可以使用Paint.measureText測量文本的長度 - 但需要設置油漆性質相同TextView的顯示屬性(TEXTSIZE,texyStyle,字體等) http://developer.android.com/reference/android/graphics/Paint.html#measureText(java.lang.String,INT, int)

你應該能夠得到一個體面的文本長度測量 - 它給你一個像素的六分之一,你可以使用它來設置列表行中所有名稱textViews的佈局參數。

0

您是否需要在最長名稱後面開始的值?或者只是爲了能夠顯示最長的名字?那麼我會建議(並在類似的問題中)沒有使用LinearLayout,而是使用RelativeLayout。

在那裏你會定義兩個TextViews,其中一個會在右邊有重力。從我的代碼中可以看出,正確的字段總是相同的大小,對嗎?所以,根據這個調整它,讓剩下的空間可以被填滿。 我的一個例子佈局:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:background="@drawable/list_selector" 
    android:orientation="horizontal" 
    android:padding="3dip" > 

<!-- Name--> 
<TextView 
    android:id="@+id/name" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentLeft="true" 
    android:textColor="#040404" 
    android:typeface="sans" 
    android:textSize="20dip" 
    android:text="Name" 
    android:textStyle="bold"/> 

<!-- Amount --> 
<TextView 
    android:id="@+id/amount" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentRight="true" 
    android:gravity="right" 
    android:layout_marginRight="5dip" 
    android:text="money" 
    android:textSize="20dip" 
    android:textColor="#FF8B1500" 
    android:textStyle="bold" 
    /> 
</RelativeLayout> 

,因爲它需要和左留給姓名權的TextView填充儘可能多的空間。

希望我幫忙給個主意!