Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend an Android button and use an xml layout file

Tags:

android

button

I'm trying to extend the android button class and have it use an xml layout file.

The reason I want to use an xml layout file is that my button needs to use a style and as far as I know, there isn't a way to set style programatically.

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 have it create a button that has the style applied to it.

(I'm also open to other ways of getting the same result)

like image 869
ajma Avatar asked Apr 20 '12 23:04

ajma


People also ask

Why layouts are created using XML file in Android?

Using XML files also makes it easy to provide different layouts for different screen sizes and orientations (discussed further in Supporting Different Screen Sizes). The Android framework gives you the flexibility to use either or both of these methods to build your app's UI.

Does Android still use XML?

We must define our own Tags. Xml as itself is well readable both by human and machine. Also, it is scalable and simple to develop. In Android we use XML for designing our layouts because XML is lightweight language so it doesn't make our layout heavy.

How XML is used in Android?

XML stands for eXtensible Markup Language, which is a way of describing data using a text-based document. Because XML is extensible and very flexible, it's used for many different things, including defining the UI layout of Android apps.


2 Answers

In your layout .xml a one line change to the control type (change from Button to your custom button type ) will solve your casting problem.

For your subclassed BuyButton, find the button's section in .xml; it may 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" />
like image 198
Joe Seibert Avatar answered Oct 17 '22 03:10

Joe Seibert


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 reference that custom class directly.

<?xml version="1.0" encoding="utf-8"?>  
<your.package.name.BuyButton 
xmlns:android="http://schemas.android.com/apk/res/android" 
style="@style/customButton"/>
like image 26
adneal Avatar answered Oct 17 '22 04:10

adneal