-1

I want to learn - if there is a way - how to define a custom view type, and use it in XML layouts.

For example, I have a custom button that looks like this:

<LinearLayout>
 <ImageView />
 <TextView />
</LinearLayout>

I know I can save this as mybutton.xml, and do <include layout="@layout/mybutton" />, but is there a way that I can use this like this:

<MyButton /> 

?

I would also like to be able to instantiate this new, custom class in Java code. Like this :

MyButton mb = new MyButton();

Should I define MyButton as a Java class? If so, what should I extend, and how ?

Thanks for any help !

jeff
  • 13,055
  • 29
  • 78
  • 136

1 Answers1

1

You will need to define a custom class for your object.

MyButton.java

public class MyButton extends View{}

You will have to create the constructor to inflate your XML document, and then call the object in your XML by the fully qualified package name.

<com.example.MyButton/>
Matt Clark
  • 27,671
  • 19
  • 68
  • 123