2012-05-29 43 views
4

我想創建一個佈局(使用eclipse),我需要垂直對齊像TextView和Button這樣的各種控件。我試圖讓所有的小部件完全左對齊。即使我爲控件指定了相同的左邊距/填充,仍然可以在不同類型的控件之間看到1-2像素的差異。Android的UI部件垂直對齊問題

問題是窗口小部件的邊框(eclipse中的藍色矩形)與窗口小部件的內容/圖形之間的距離因部件(如TextView和Button)而異。

我可以通過爲TextView指定左填充或通過減少按鈕容器的左邊距來應用解決方法。但我正在尋找更清潔的解決方案。我無法找到任何控制小部件邊框和內容之間區別的屬性。 任何關於如何控制這種差距的指針?

快照顯示問題如下。下面是我用於此問題的佈局XML: -

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="vertical" > 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Hello World" /> 

    <Button 
     android:id="@+id/button1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Dummy Button" /> 

</LinearLayout> 

下面的圖像顯示了虛擬應用程序的快照。請注意「Hello World」TextView和「虛擬按鈕」的左側邊距之間的差異。

第二張圖片顯示了在Eclipse中選中時的按鈕小部件。藍色矩形指示小部件邊界/邊界。按鈕的邊框(藍色矩形)和內容(灰色矩形)之間的區別是否可以通過某些屬性控制?

Dummy Application Snapshot Button with boundary

+1

粘貼到快照的鏈接,我將編輯問題以顯示它。 – Blundell

+1

你現在有超過10分:) –

+0

添加了圖像,謝謝你的分數:) –

回答

2

這是一個艱難的一個TextView的和其他Android部件可能有一些固有風格的自己(Android版本依賴爲好)。

因此,要解決這個問題,你必須創建自己的風格。

在創造自己的風格始終引用在這個問題上Android源代碼:

https://github.com/android/platform_frameworks_base/tree/master/core/res/res/values

https://github.com/android/platform_frameworks_base/blob/master/core/res/res/values/themes.xml

https://github.com/android/platform_frameworks_base/blob/master/core/res/res/values/styles.xml

有多種方式來創建你自己的風格。

一種方法是在您的清單中主題您的活動。 首先,您需要一個styles.xml文件,位於/ values /文件夾中。 在這裏,你將宣佈新的風格:

<style name="Theme.MyTheme.Dark" parent="@android:style/Theme.NoTitleBar"> 
    <item name="android:textViewStyle">@style/Widget.TextView.Black</item> 
</style> 

<style name="Theme.MyTheme.Light" parent="@android:style/Theme.NoTitleBar"> 
    <item name="android:textViewStyle">@style/Widget.TextView.White</item> 
</style> 

上面它從Android的風格,隱藏標題欄繼承的樣式,你可以從別的繼承。 在這個主題中,我們重寫textViewStyle,這允許我們爲我們的TextView設置自定義值並覆蓋一些內在值。

<style name="Widget.TextView.White" parent="@android:style/Widget.TextView"> 
    <item name="android:textColor">#FFFFFF</item> 
</style> 

<style name="Widget.TextView.Black" parent="@android:style/Widget.TextView"> 
    <item name="android:textColor">#000000</item> 
</style> 

最後,您在AndroidManifest中主題您的活動。xml:

 <activity 
     android:name=".ui.phone.FirstActivity" 
     android:theme="@style/Theme.MyTheme.Dark" /> 

    <activity 
     android:name=".ui.phone.SecondActivity" 
     android:theme="@style/Theme.MyTheme.Light" /> 

現在,當您在FirstActivity中使用TextView時,文本將默認爲黑色,在第二個活動中它將爲白色。

爲您的具體問題:

你將不得不去看看在我在上面鏈接的源代碼文件,看看是否有任何填充或minWidth或正在影響你的widget和大小屬性的佈局。

+0

感謝您的回覆。默認情況下,按鈕使用「btn_default」爲「android:background」屬性的樣式Widget.Button。 btn_default指定另一個資源「btn_default_normal」。我無法在android sdk或github的主樹中找到btn_default_normal的定義。但我認爲我可能必須編寫自己的自定義樣式。 –