2011-08-17 329 views
2

我想創建一個3行按鈕的佈局,並且我想讓它們中的每一個寬度爲屏幕寬度的30%。 這樣做的最好方法是什麼?按鈕大小和按鈕按下背景顏色的變化

我的第二個問題是, 如何定義按鈕的按下顏色? 我希望按鈕變成綠色,按下時變成紅色。

謝謝! 馬爾科

+0

你想讓它們在發佈時再次變成綠色嗎? – MByD

+0

是的,回到綠色:) –

回答

5

做顏色的按鈕,最好的辦法是爲您創建自定義可繪按鈕,當按下/活動/殘疾/集中(在我的例子中,我使用button_faded.png,button_down.png & button_up.png)然後定義一個xml來告訴按鈕如何使用它:

button.xml:

<?xml version="1.0" encoding="utf-8"?> 

<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
    <item android:drawable="@drawable/button_faded" 
      android:state_enabled="false" /> 
    <item android:drawable="@drawable/button_down" 
      android:state_pressed="true" /> 
    <item android:drawable="@drawable/button_up" 
      android:state_focused="true" /> 
    <item android:drawable="@drawable/button_up" /> 
</selector> 

然後在你的佈局將背景設置爲"@drawable/button"

或在您的styles.xml更好的創建按鈕樣式:

<style name="Button"> 
    <item name="android:layout_width">fill_parent</item> 
    <item name="android:layout_height">wrap_content</item> 
    <item name="android:textColor">#000000</item> 
    <item name="android:textSize">19sp</item> 
    <item name="android:background">@drawable/button</item> 
    <item name="android:gravity">center</item> 
    <item name="android:paddingLeft">0dp</item> 
    <item name="android:paddingRight">0dp</item> 
    <item name="android:paddingTop">5dp</item> 
    <item name="android:paddingBottom">5dp</item> 
</style> 

,並在佈局XML告訴按鈕使用的樣式:

<Button style="@style/Button" /> 

只要按鈕的佈局...如果你正在尋找每個屏幕的1/3,創建一個水平的LinearyLayout con保留了所有三個按鈕。將按鈕寬度設置爲fill_parent,並給它們所有相同的佈局權重,比如說'1'...這應該用3個按鈕填充行,每個按鈕的大小相同。然後,您可以使用佈局邊距或填充來調整它們之間的空間。

1
Display mDisplay= activity.getWindowManager().getDefaultDisplay(); 
int width= mDisplay.getWidth(); 
int Height= mDisplay.getHeight(); 

if(width>height) 
{ 
//Landscape 
//set your landscape drawable 
} 
else 
{ 
//portrait 
//set your portrait drawable 
} 

現在採取寬度可變的30%,而對於顏色只是用不同的狀態繪製看到here