How to extend android button and use xml layout file

I am trying to extend the Android button class and use the xml layout file.

The reason I want to use the xml layout file is because my button needs to use a style and, as far as I know, there is no way to set the style programmatically.

public class BuyButton extends Button {...}

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

so that I can call:

 new BuyButton(activity); 

and create a button that has a style applied to it.

(I am also open to other ways to get the same result)

+8
android button
source share
3 answers

Create a class that extends Button .

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

In your XML link, this user class is directly.

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

In your .xml layout, changing one line to the type of control (changing from a button to a custom button type) will solve your cast problem.

For your BuyButton subclass, find the button section in .xml; it might look something like this:

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

and change it to this:

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

See Button Style . Just set a custom wallpaper.

-one
source share

All Articles