2012-04-20 135 views
8

我試圖擴展android按鈕類並讓它使用xml佈局文件。如何擴展Android按鈕並使用xml佈局文件

我想使用xml佈局文件的原因是,我的按鈕需要使用樣式,據我所知,沒有辦法以編程方式設置樣式。

公共類BuyButton擴展按鈕{...}

<?xml version="1.0" encoding="utf-8"?> 
<Button 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    style="@style/customButton" 
/> 

,這樣我可以打電話:

new BuyButton(activity); 

,並將它創建具有應用的樣式按鈕它。

(我也開到得到同樣結果的其他方式)

回答

15

創建擴展Button類。

public class BuyButton extends Button { 

    public BuyButton(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     // TODO Auto-generated constructor stub 
    } 

} 

在您的XML引用中直接定製類。

<?xml version="1.0" encoding="utf-8"?> 
<your.package.name.BuyButton 
xmlns:android="http://schemas.android.com/apk/res/android" 
style="@style/customButton"/> 
+2

我得到一個運行時錯誤。它正在抱怨xml。 04-20 16:30:19.852:E/AndroidRuntime(18583):android.view.InflateException:二進制XML文件行#2:錯誤膨脹類client.views.buttons.BuyButtonView – ajma 2012-04-20 23:33:36

+0

謝謝!謝謝你!謝謝你!完美的答案! – gran33 2013-03-16 09:15:29

-1

請參閱Button Style部分。只需設置一個自定義背景可繪製。

+1

我不能做自定義的背景drawable。它必須是一種風格。 – ajma 2012-04-20 23:32:37

1

在佈局.xml中,一行更改爲控件類型(從Button更改爲您的自定義按鈕類型)將解決您的投射問題。

對於您的子類別BuyButton,請在.xml中找到該按鈕的部分;它可能是這個樣子:

<Button 
      android:id="@+id/btnBuy" 
      android:layout_width="188dp" 
      android:layout_height="70dp" 
      android:padding="12dp" 
      android:text="Buy" /> 

它改成這樣:

<yourpackage.name.BuyButton 
      android:id="@+id/btnBuy" 
      android:layout_width="188dp" 
      android:layout_height="70dp" 
      android:padding="12dp" 
      android:text="Buy" /> 
+0

也必須在你的子類中有一個構造函數來允許通貨膨脹;你也可以創建具有不同簽名的其他構造函數,但是必須在你的子類中定義帶有上下文和屬性參數的基本構造函數。請參閱:https://sholtz9421.wordpress.com/2012/03/22/correct-way-to-subclass-android-views/ – 2017-05-14 08:03:50