There are a lot of custom controls in Android, and generally custom controls can be divided into two types: inherited controls and composite controls. The former is to implement custom display and event handling by inheriting view or its subclasses, the latter by combining existing controls to simplify the structure and reuse code.
This article focuses on custom composite controls, and subsequent opportunities for inheriting controls are described later.
Custom composite controls are generally based on ViewGroup and their subclasses (LinearLayout, Relativelayout, Framelayout, and so on), nested inside other controls, to combine them into a new control, to achieve some specific needs, can be code simplification, The structure is clear and reusability is high.
Typically, we implement the definition of the good one layout.xml file, and then let our custom control load the XML and get the child controls, and then set the properties (which can be loaded through code or from a resource file), adding events.
Customization Essentials:
1. Loading the XML file is done in the constructor method, by calling inflate (R.layout.my_layout,This,true), noting the second and third parameters;
2. If you need to load a custom property from a resource file, you must override constructor (context context, AttributeSet Attrs) This constructor method, which is defined in Attrs.xml;
3. Gets the child control object, can be obtained in the construction method, can also override the Onfinishinflate () method to obtain, the personal suggestion adopts the second kind, can guarantee that the control has fully loaded well;
4. Add event can be written directly in the control, but considering the extensibility and reusability, it is recommended to expose the interface to the outside.
Sample Code (the code is simple, just describe the idea)
Custom Control Layout:header.xml
<?XML version= "1.0" encoding= "Utf-8"?><Relativelayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"> <ImageButtonAndroid:id= "@+id/ib_header"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_alignparentright= "true"android:layout_centervertical= "true"android:src= "@android:d rawable/ic_menu_zoom" /> <TextViewAndroid:id= "@+id/tv_header"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"android:layout_centerinparent= "true" /></Relativelayout>
Custom control class: Header.java
Packagecom.ivan.app1.widgets;ImportCOM.IVAN.APP1.R;ImportAndroid.content.Context;ImportAndroid.content.res.TypedArray;ImportAndroid.graphics.Color;Importandroid.text.TextUtils;ImportAndroid.util.AttributeSet;ImportAndroid.view.LayoutInflater;ImportAndroid.widget.ImageButton;Importandroid.widget.LinearLayout;ImportAndroid.widget.TextView;/*** Custom title bar combo control, internal contains a textview and a ImageButton * user:xyh * DATE:2015/6/2 * time:9:39*/ Public classHeaderextendsRelativelayout {PrivateTextView Mtextview; PrivateImageButton Mimagebutton; PrivateString TitleText; Private intTitletextcolor; Private floattitletextsize; PublicHeader (Context context) {Super(context); } PublicHeader (Context context, AttributeSet attrs) {Super(context, attrs); //load the layout of the viewLayoutinflater.from (context). Inflate (R.layout.header, This,true); //to load a custom propertyTypedArray a=context.obtainstyledattributes (Attrs,r.styleable.header); TitleText=a.getstring (R.styleable.header_titletext); Titletextcolor=A.getcolor (R.styleable.header_titletextcolor, Color.White); Titletextsize=a.getdimension (r.styleable.header_titletextsize,20f); //Recycle resources, this sentence must be calleda.recycle (); } /*** This method is called after all controls have been loaded from the XML file .*/@Overrideprotected voidonfinishinflate () {Super. Onfinishinflate (); //Get child controlsmtextview=(TextView) Findviewbyid (R.id.tv_header); Mimagebutton=(ImageButton) Findviewbyid (R.id.ib_header); //To set a property loaded from a resource file to a child control if(!Textutils.isempty (TitleText)) Setpagetitletext (TitleText); Setpagetitletextcolor (Titletextcolor); Setpagetitletextsize (titletextsize); } /*** Set Title text *@paramtext*/ Public voidSetpagetitletext (String text) {mtextview.settext (text); } /*** Set Title text color *@paramColor*/ Public voidSetpagetitletextcolor (intcolor) {Mtextview.settextcolor (color); } /*** Set Title text size *@paramsize*/ Public voidSetpagetitletextsize (floatsize) {mtextview.settextsize (size); } /*** Set Button click event Listener *@paramListener*/ Public voidSetonheaderclicklistener (Onclicklistener listener) {Mimagebutton.setonclicklistener (listener); }}
Custom properties File: Attrs.xml
<?XML version= "1.0" encoding= "Utf-8"?><Resources> <!--Custom Properties - <declare-styleablename= "Header"> <attrname= "Titletextsize"format= "Dimension" /> <attrname= "Titletextcolor"format= "Color" /> <attrname= "TitleText"format= "string"/> </declare-styleable></Resources>
Here is how to refer to the Activity layout file: Main.xml
<?XML version= "1.0" encoding= "Utf-8"?><LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:app= "Http://schemas.android.com/apk/res-auto"android:orientation= "vertical"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"> <!--Note that you need to add a namespace in the Eclipse development tool: Use xmlns:app= "Http://schemas.android.com/apk/res/com.ivan.app1.widgets" in the IntelliJ Id When building with Gradle in EA or Android studio, use xmlns:app= "Http://schemas.android.com/apk/res-auto" - <!--to refer to a custom view by the full name of the package's class - <Com.ivan.app1.widgets.HeaderAndroid:id= "@+id/header"Android:layout_width= "Match_parent"Android:layout_height= "48DP"Android:background= "@color/black"App:titletext= "I am the title"App:titletextcolor= "#ff0000"app:titletextsize= "12SP"/> <TextViewAndroid:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:gravity= "Center"Android:text= "I am Content"android:textsize= "60SP"/></LinearLayout>
Main activity class: Mainactivity.java
PackageCom.ivan.app1;ImportCom.ivan.app1.widgets.Header;ImportAndroid.os.Bundle;Importandroid.support.v7.app.AppCompatActivity;ImportAndroid.view.View;ImportAndroid.widget.Toast;/*** USER:XYH * DATE:2015/6/2 * time:10:30*/ Public classMainactivityextendsappcompatactivity {@Override Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.main); (Header) Findviewbyid (R.id.header)). Setonheaderclicklistener (NewView.onclicklistener () {@Override Public voidOnClick (View v) {toast.maketext (Getapplicationcontext (),"The button for the title bar is clicked.", Toast.length_long). Show (); } }); }}
Operation Result:
Original articles, reproduced please indicate the source.
Custom Combo Controls in Android