2012-10-18 19 views
0
<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
      android:shape="rectangle">  
    <solid android:color="#EAEAEA"/>  

    <corners android:bottomLeftRadius="5dip" 
       android:topRightRadius="5dip" 
       android:topLeftRadius="5dip" 
       android:bottomRightRadius="5dip" 
    /> 
</shape> 

如何將我的gradient image設置爲我的按鈕的背景。我看到一個屬性漸變,但看不到任何其中包含背景的屬性。Android:設置按鈕的自定義漸變

注意:我是非常新的Android開發。

回答

3

我不確定您向我們展示的XML與漸變有什麼關係。您可以在drawable文件夾中定義的XML文件中的梯度:

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <gradient 
     android:startColor="#FFFFFFFF" 
     android:endColor="#FFD9D9D9" 
     android:angle="270" 
    /> 
    <corners android:bottomLeftRadius="5dip" 
      android:topRightRadius="5dip" 
      android:topLeftRadius="5dip" 
      android:bottomRightRadius="5dip" 
    /> 
</shape> 

(例如,它保存爲my_gradient.xml)在您的佈局xml文件

然後,你可以有:

<Button android:id="@+id/ButtonStart" 
    android:layout_width="100dp" android:layout_height="wrap_content" 
    android:background="@drawable/my_gradient" 
    android:textColor="@color/white" android:textSize="14sp" 
    android:textStyle="bold" android:text="@string/game_start"/> 
2

您應該在XML中定義漸變或使用圖像(將包含圓角)。你不能輕易地將XML形狀和圖像混合在一起(至少,因爲你是初學者,我建議先用簡單的東西去做)。

例如:

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <gradient 
     android:startColor="#474946" 
     android:endColor="#181818" 
     android:angle="270"/> 
    <corners android:radius="5dp" /> 
</shape> 

然後你可以使用定義按鈕的背景android:background="@drawable/bg_custom_button"

你應該瞭解九補丁,它們允許你定義strechable圖片爲您的背景,將節省您當設計對XML不可行時。

2

你的形狀是朝着正確的方向發展,但不是堅實的你可以使用漸變

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
     android:shape="rectangle">  
    <gradient 
     android:angle="270" 
     android:endColor="@color/gradient_bottom" 
     android:startColor="@color/gradient_top" />  

    <corners android:bottomLeftRadius="5dip" 
      android:topRightRadius="5dip" 
      android:topLeftRadius="5dip" 
      android:bottomRightRadius="5dip" 
    /> 
</shape> 

假設上述形狀保存爲gradient_background.xml,並將其保存在可繪製文件夾中(它應該在的位置)。您現在可以使用此可繪製項目作爲您的按鈕的背景

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:background="@drawable/gradient_background" 
    android:text="Button" />