2012-05-21 72 views
7

請讓我知道,如何將自定義按鈕的默認背景設置爲null。在自定義視圖中提供默認樣式(屬性)

我的意思是... 我知道我可以定義一個將android:background設置爲「@null」, 的「style」,並要求用戶在其佈局中明確應用樣式。例如:

<style name="MyButton" parent="@android:style/Widget.Button"> 
    <item name="android:background">@null</item> 
</style> 

<com.xxx.widget.MyButton 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    style="@style/MyButton" 
    android:text="MyButton" /> 

上面的代碼是運作良好。 但是我怎樣才能在我的班級「MyButton」內部應用這種風格,並讓用戶不要明確設置樣式?

例如,如何使以下佈局和以前一樣:

<com.xxx.widget.MyButton 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text="MyButton" /> 

我試圖做到這一點,如下圖所示的構造,但它不工作。

public MyButton(Context context, AttributeSet attrs) { 
    this(context, attrs, com.xxx.R.style.MyButton); 
} 

PS。我想在用戶不明確設置背景 時應用此「空白」背景。

+0

我想你應該改變你的問題的標題。您始終可以擁有默認樣式,但稍後可以更改。也許你需要說'最終風格'或​​類似的東西 – ikbal

+1

請參閱http://stackoverflow.com/questions/4493947/how-to-define-theme-style-item-for-custom-widget關於此的一些提示。 –

+0

有類似的要求:http://stackoverflow.com/questions/31504413/theme-style-for-custom-view/31505624#31505624 – stefan

回答

0

在你的MyButton()構造函數中,爲什麼不調用setBackground(null)?

0

這或多或少是一種便宜的方法,但爲什麼不將背景設置爲透明正方形。這樣的 - >

transparent_square.xml:(把它放在繪製目錄)

<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/square" 
    android:> 

    <solid android:color="#00808080"></solid> // The first two zeros set the alpha 
               // to 0 

</shape> 

然後按鈕的背景設置爲您繪製。

按鈕:

<Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Send" 
     android:id="@+id/sendButton" 
     android:layout_weight="1" 
     android:background="@drawable/transparent_square"/> 
相關問題