Three ways to implement Android custom view

Source: Internet
Author: User

In summary, there are three ways to implement a custom control, namely, a composite control, a self-drawing control, and an inherited control. These three methods are described separately below.

(i) Composite controls

The combination of controls, as the name implies, is the combination of small controls to form a new control, which is mostly the system's own control. For example, many applications commonly used in the title bar control, its practical is the combination of controls, then the following will be implemented by a simple title bar custom control to say the use of composite controls.

1. Create a new Android project, creating a custom title bar layout file Title_bar.xml:

1 <?xml version= "1.0" encoding= "Utf-8"?> 2 <relativelayout xmlns:android= "http://schemas.android.com/apk/ Res/android "3     android:layout_width=" match_parent "4     android:layout_height=" Wrap_content "5     android: background= "#0000ff" > 6  7     <button 8         android:id= "@+id/left_btn" 9         android:layout_width= "Wrap _content "Ten         android:layout_height=" Wrap_content "one         android:layout_centervertical=" true "         Android: Layout_margin= "5DP"         android:background= "@drawable/back1_64"/>14     <textview16         android: Id= "@+id/title_tv"         android:layout_width= "wrap_content" android:layout_height= "         wrap_content" 19         android:layout_centerinparent= "true"         android:text= "This is the title"         android:textcolor= "#ffffff" 22         android:textsize= "20SP"/>23 </RelativeLayout>

Visible this title bar control is still relatively simple, in which there is a return button on the left, the background is a prepared picture back1_64.png, the title bar is the title text in the middle.

2, create a class Titleview, inherit from Relativelayout:

1 public class Titleview extends Relativelayout {2  3     //Return button control 4     private button mleftbtn; 5     //title TV 6
   
    private TextView Mtitletv; 7  8 Public     Titleview (context context, AttributeSet Attrs) {9         super (context, attrs);         //Load Layout 12         Layoutinflater.from (context). Inflate (R.layout.title_bar, this); +         //Get control at         mleftbtn = (Button) Findviewbyid (R.ID.LEFT_BTN),         Mtitletv = (TextView) Findviewbyid (R.ID.TITLE_TV),}19     // Add a custom Click event for the left return button public     void Setleftbuttonlistener (Onclicklistener listener) {         Mleftbtn.setonclicklistener (listener);     }24     //To set the title method of the public     void Settitletext (String title) {         Mtitletv.settext (title);     }29}
   

In Titleview, the layout is loaded primarily for a custom title bar, an event listener method is added for the Back button, and a method for setting the caption text is provided.

3. Introduce a custom title bar in Activity_main.xml:

1 <linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" 2     android:id= "@+id/main_layout" 3     android:layout_width= "match_parent" 4     android:layout_height= "Match_parent" 5     android:orientation= " Vertical "> 6  7     <com.example.test.titleview 8         android:id=" @+id/title_bar "9         android:layout_ Width= "Match_parent"         android:layout_height= "wrap_content" >11     </com.example.test.titleview >12 </LinearLayout>

4. Get the custom title bar in Mainactivity and add a custom click event for the Back button:

1 private Titleview Mtitlebar; 2 Mtitlebar = (Titleview) Findviewbyid (R.id.title_bar); 3  4         mtitlebar.setleftbuttonlistener (new Onclicklistener () {5  6             @Override 7 public             void OnClick ( View v) {8                 toast.maketext (mainactivity.this, "Click Back Button", Toast.length_short) 9                         . Show ();                 finish (); 11             }12         });

5, the operation effect is as follows:

  

In this way, the custom title bar is implemented in a combination, and more complex custom controls, such as custom search bars, can be created through more combinations.

(ii) Self-drawing controls

  The content of the self-drawing control is drawn by itself and is done in the view's OnDraw method. The following implementation of a simple counter, each click on it, the count value is added 1 and displayed.

1, create Counterview class, inherit from view, implement Onclicklistener interface:

 1 public class Counterview extends View implements Onclicklistener {2 3//definition Brush 4 private Paint mpaint; 5/ /used to get the width and height of text 6 private Rect mbounds; 7//Count value, once per click the control, its value increased by 1 8 private int mCount; 9 Public Counterview (context context, AttributeSet Attrs) {One super (context, attrs); 12 13//initialization brush,         Rect14 mpaint = new Paint (paint.anti_alias_flag), mbounds = new Rect (); 16//Click event for this control 17 Setonclicklistener (this),}19 @Override21 protected void OnDraw (canvas canvas) {Super.ondraw (c Anvas); Mpaint.setcolor (color.blue); 25//Draw a rectangle filled with blue color canvas.drawrect (0, 0, getwidth (), G  Etheight (), mpaint); Mpaint.setcolor (Color.yellow); mpaint.settextsize (+); String Text =         String.valueof (MCount); 31//Get text width and height of mpaint.gettextbounds (text, 0, Text.length (), mbounds); 33 float textWidth = Mbounds.width ();TextHeight = Mbounds.height (); 35 36//Draw String PNs Canvas.drawtext (text, getwidth ()/2-TEXTWIDTH/2, gethe         Ight ()/238 + TEXTHEIGHT/2, mpaint);}40 @Override42 public void OnClick (View v) {43 MCount ++;44 45//Redraw invalidate (); 47}48 49}

2. Introduce the custom layout in Activity_main.xml:

1 <linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" 2     android:id= "@+id/main_layout" 3     android:layout_width= "match_parent" 4     android:layout_height= "Match_parent" 5     android:orientation= " Vertical "> 6  7     <com.example.test.counterview 8         android:id=" @+id/counter_view "9         android: Layout_width= "100DP"         android:layout_height= "100DP" one-         android:layout_gravity= "Center_horizontal|top "         android:layout_margin=" 20DP "/>13 </LinearLayout>

3, the operation effect is as follows:

(iii) Inherited controls

  is to inherit existing controls, create new controls, preserve the attributes of inherited parent controls, and introduce new features. The following is an introduction to the implementation of a custom ListView that supports horizontal swipe to delete list items.

1. Create Delete button layout delete_btn.xml, this layout is displayed after sliding the list item horizontally:

1 <?xml version= "1.0" encoding= "Utf-8"?> 2 <button xmlns:android= "http://schemas.android.com/apk/res/ Android "3     android:layout_width=" wrap_content "4     android:layout_height=" Wrap_content "5     android: Background= "#FF0000" 6     android:padding= "5DP" 7     android:text= "Delete" 8     android:textcolor= "#FFFFFF" 9     Android:textsize= "16SP" >10 </Button>

2. Create the Customlistview class, inherit from the ListView, and implement the Ontouchlistener and Ongesturelistener interfaces:

  1 public class Customlistview extends ListView implements Ontouchlistener, 2 Ongesturelistener {3 4//  Gesture Action Detector 5 private gesturedetector mgesturedetector; 6 7//Delete Event Listener 8 public interface Ondeletelistener {9 void onDelete (int index); Rivate Ondeletelistener Mondeletelistener; 13 14//Delete button the private View mdeletebtn; 16 17//list item layout ViewGroup mitemlayout; 19 20//Selected list item + private int mselecteditem; 22 23//The current Delete button is displayed. The private Boolean isdeleteshown; Customlistview Public (context context, AttributeSet attrs) (context, attrs); 28 29/ /create gesture Listener Object mgesturedetector = new Gesturedetector (GetContext (), this); 31 32//Monitor Ontouch event Setontouchlistener (this); 34} 35 36//Set Delete listener event Notoginseng public void Setondeletelistener (Ondeletelistener listener) {Mondeleteli Stener = listener; 39} 40 41//Touch Monitor Event @Override public boolean OnTouch (View V, motionevent event) {Isdeleteshown ) {hidedelete (); return false; n} else {return MGESTUREDETECTOR.O Ntouchevent (event); ($) @Override (motionevent e) {Ondown (!isdeleteshown) { Mselecteditem = pointtoposition ((int) e.getx (), (int) e.gety ()); *.             62 (motionevent E1, motionevent E2, float Velocityx, onfling) @Override Float velocityy) {63//If the current Delete button is not displayed, and the X-direction slide speed is greater than the sliding speed in the Y-direction (!isdeleteshown && Math.Abs (v                     Elocityx) > Math.Abs (velocityy)) {mdeletebtn = Layoutinflater.from (GetContext ()). Inflate (66 R.LAYOUT.DELETE_BTN, NULL);             Mdeletebtn.setonclicklistener (New Onclicklistener () {69 70    @Override the public void OnClick (View v) {Mitemlayout.removeview (MDELETEBTN); MDELETEBTN = null; Isdeleteshown = false; Mondeletelistener.ondelete (Mselecteditem); 76} 77});  Mitemlayout = (viewgroup) getchildat (Mselecteditem 80-getfirstvisibleposition ()); Bayi relativelayout.layoutparams params = new Relativelayout.layoutparams (layoutpar Ams. Wrap_content, layoutparams.wrap_content); Params.addrule (Relativelayout.align_parent_right); Params.addrule (relativelayout.center_vertical); Mitemlayout.addview (mdeletebtn, params); Isdeleteshown = true; "A."         92} 93 94//Hide Delete button Mitemlayout.removeview public void Hidedelete () {(MDELETEBTN); 97 MdelETEBTN = null; 98 Isdeleteshown = false;      }100 101 Public boolean Isdeleteshown () {102 return isdeleteshown;103}104 105/**106 * The following methods are not used in this example 107 */108 @Override109 public void onshowpress (Motionevent e) {111}112 113 @Overr ide114 public boolean onsingletapup (Motionevent e) {* * * return false;116}117 118 @Override119 Pub Lic boolean onscroll (motionevent E1, motionevent E2, float distancex,120 float Distancey) {121 return false;122}123 124 @Override125 public void onlongpress (Motionevent e) {126 127}128 129}

3, the definition of the list item layout custom_listview_item.xml, its structure is very simple, contains only one textview:

1 <?xml version= "1.0" encoding= "Utf-8"?> 2 <relativelayout xmlns:android= "http://schemas.android.com/apk/ Res/android "3     android:layout_width=" match_parent "4     android:layout_height=" Match_parent "5     android: descendantfocusability= "Blocksdescendants" > 6  7     <textview 8         android:id= "@+id/content_tv" 9         Android:layout_width= "Wrap_content" ten         android:layout_height= "Wrap_content"         android:layout_ Centervertical= "true"         android:layout_margin= "30DP"         android:gravity= "Center_vertical|left"/>14 </RelativeLayout>

4, defines the adapter class Customlistviewadapter, inherits from Arrayadapter<string>:

1 public class Customlistviewadapter extends arrayadapter<string> {2  3 public     Customlistviewadapter ( Context context, int Textviewresourceid, 4             list<string> objects) {5         super (context, Textviewresourceid, objects); 6     } 7  8     @Override 9 public     view GetView (int position, View Convertview, ViewGroup parent) {Ten         View VI Ew;11         if (Convertview = = null) {             view = Layoutinflater.from (GetContext ()). Inflate (                     R.layout.custom_listview_item, null);         \ n} else {             view = convertview;17         }18         TextView Contenttv = (TextView) View.findviewbyid (R.ID.CONTENT_TV),         Contenttv.settext (GetItem (position));         return view;23     }24 25}

5. Introduce the custom ListView in Activity_main.xml:

1 <linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" 2     android:id= "@+id/main_layout" 3     android:layout_width= "match_parent" 4     android:layout_height= "Match_parent" 5     android:orientation= " Vertical "> 6  7     <com.example.test.customlistview 8         android:id=" @+id/custom_lv "9         android: Layout_width= "Match_parent"         android:layout_height= "wrap_content"/>11 </LinearLayout>

6, in mainactivity to initialize the list, set the list item Delete button click event Processing:

 1 public class Mainactivity extends Activity {2 3//Custom LV 4 private Customlistview MCUSTOMLV; 5//Custom Adapter 6 private Customlistviewadapter Madapter; 7//Content List 8 private list<string> ContentList = new arraylist<string> (); 9 @Override11 protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate)         ; Requestwindowfeature (Window.feature_no_title); Setcontentview (R.layout.activity_main); 15 16 Initcontentlist (); mcustomlv = (Customlistview) Findviewbyid (R.ID.CUSTOM_LV); mcustomlv.setondelete                 Listener (New Ondeletelistener () {@Override22 public void onDelete (int index) {23         Contentlist.remove (index); madapter.notifydatasetchanged (); 25}26}); 27 28     Madapter = new Customlistviewadapter (this, 0, contentlist); Mcustomlv.setadapter (madapter); 30}31 32 Initialize insideTolerance List initcontentlist () {i++ for (int i = 0; I <) {Contentlist.add ("Content item")  + i);}37}38 @Override40 public void onbackpressed () {if (Mcustomlv.isdeleteshown ())  {Mcustomlv.hidedelete (); return;44}45 super.onbackpressed (); 46}47 48}

7, the operation effect is as follows:

refer:http://blog.csdn.net/guolin_blog/article/details/17357967

Three ways to implement Android custom view

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.