Android custom controls, setting the button's style dynamically

Source: Internet
Author: User

Original http://www.cnblogs.com/landptf/p/4562203.html


Today, let's take a look at a button to dynamically implement some effects, such as rounded rectangle, circle, press to change the font, change the background color, change the background map, etc.

In this case, this implementation is absolutely not unique, and is simple to implement through an XML file, just to make the control's style completely code-based and easier to package for other projects

Here's a look:

Figure 1 Initial state Figure 2 Press the TEXT0 of the first line

Figure 3 Pressing the second row of TEXT1 Figure 4 Press the TEXT2 of the third row, while holding down the screenshot, there is no prompt to intercept the toast

See the code below for a total of two classes, one layout file

1 Buttonm.java: Override button, can be individually packaged for other projects

Package Landptf.control;import Android.content.context;import Android.graphics.color;import Android.graphics.drawable.gradientdrawable;import Android.util.attributeset;import Android.view.Gravity;import Android.view.motionevent;import android.view.view;import android.widget.button;/** * Override button, customize button style * @author LANDPTF * @date 2015-6-8 */public class Buttonm extends button{private gradientdrawable gradientdrawable;//control style privat E string backcolors = "";//Background color, String type private int backcolori = 0;//background color, int type private String backcolorselecteds = "";// Pressed background color, string type private int backcolorselectedi = 0;//pressed background color, int type private int backgroundimage = 0;//background graph, only ID privat provided e int backgroundimageseleted = 0;//pressed background image, only provided ID private String textcolors = "";//Text color, String type private int Textcolori = 0;//text color, int type private String textcolorseleteds = "",//Pressed text color, String type private int textcolorseletedi = 0;//pressed text color, int type Private Float radius = 8;//fillet radius private int shape = 0;//fillet style, Rectangle, round, and so on, since the rectangle has an ID of 0, the default is rectangle private Boolean fillet = false;//whether to set fillet public buttonm (context context, AttributeSet attrs, int def    Style) {Super (context, attrs, Defstyle);  Init ();  } public Buttonm (context context, AttributeSet Attrs) {This (context, attrs, 0);  } public Buttonm (context context) {This (context, NULL); } private void Init () {//To change the default background color of the button to transparent, I do not like the original color if (fillet) {if (gradientdrawable = = null) {GR      adientdrawable = new Gradientdrawable ();    } gradientdrawable.setcolor (Color.transparent);    }else {setbackgroundcolor (color.transparent);    }//Set text Default center setgravity (gravity.center); Set Touch event Setontouchlistener (new Ontouchlistener () {@Override public boolean OnTouch (View arg0, Motioneven        T event) {//press change style SetColor (Event.getaction ());      Set to false here to prevent the Click event from being masked return false;  }    });   }//change style private void setcolor (int state) {if (state = = Motionevent.action_down) {   Press if (Backcolorselectedi! = 0) {//To determine whether the pressed background color int if (fillet) {if (GRADIENTDRAWABL) is set.          E = = null) {gradientdrawable = new gradientdrawable ();        } gradientdrawable.setcolor (Backcolorselectedi);        }else {setbackgroundcolor (Backcolorselectedi);            }}else if (!backcolorselecteds.equals ("")) {if (fillet) {if (gradientdrawable = = null) {          gradientdrawable = new Gradientdrawable ();        } gradientdrawable.setcolor (Color.parsecolor (backcolorselecteds));        }else {SetBackgroundColor (Color.parsecolor (backcolorselecteds));      }}//Determine if the color of the pressed text is set if (Textcolorseletedi! = 0) {settextcolor (Textcolorseletedi);      }else if (!textcolorseleteds.equals ("")) {SetTextColor (Color.parsecolor (textcolorseleteds)); }//Determine if the background image is set down if (backgroundimageseleted! = 0) {Setbackgroundresource (backgroundimageseleteD);        }} if (state = = motionevent.action_up) {//lift if (Backcolori = = 0 && backcolors.equals ("")) { If no background color is set, the default change is transparent if (fillet) {if (gradientdrawable = = null) {gradientdrawable = new Gra          Dientdrawable ();        } gradientdrawable.setcolor (Color.transparent);        }else {setbackgroundcolor (color.transparent); }}else if (Backcolori! = 0) {if (fillet) {if (gradientdrawable = = null) {GRADIENTDRAWABL          E = new gradientdrawable ();        } gradientdrawable.setcolor (Backcolori);        }else {setbackgroundcolor (Backcolori); }}else {if (fillet) {if (gradientdrawable = = null) {gradientdrawable = new Gradientdra          Wable ();        } gradientdrawable.setcolor (Color.parsecolor (backcolors));        }else {SetBackgroundColor (Color.parsecolor (backcolors));  }}//If the font color is set, the default is black    if (Textcolori = = 0 && textcolors.equals ("")) {SetTextColor (color.black);      }else if (Textcolori! = 0) {settextcolor (Textcolori);      }else {SetTextColor (Color.parsecolor (textcolors));      } if (BackgroundImage! = 0) {setbackgroundresource (backgroundimage); }}}/** * Sets the background color of the button, if not set, the default is transparent * @param backColor */public void Setbackcolor (String backColor) {this.ba    Ckcolors = BackColor; if (Backcolor.equals ("")) {if (fillet) {if (gradientdrawable = = null) {gradientdrawable = new Grad        Ientdrawable ();      } gradientdrawable.setcolor (Color.transparent);      }else {setbackgroundcolor (color.transparent);         }}else {if (fillet) {if (gradientdrawable = = null) {gradientdrawable = new gradientdrawable ();      } gradientdrawable.setcolor (Color.parsecolor (BackColor));      }else {SetBackgroundColor (Color.parsecolor (BackColor));  }  }}/** * Sets the background color of the button, if not set, the default is transparent * @param backColor */public void Setbackcolor (int backColor) {This.backcolo    RI = BackColor; if (Backcolori = = 0) {if (fillet) {if (gradientdrawable = = null) {gradientdrawable = new Gradientd        Rawable ();      } gradientdrawable.setcolor (Color.transparent);      }else {setbackgroundcolor (color.transparent);         }}else {if (fillet) {if (gradientdrawable = = null) {gradientdrawable = new gradientdrawable ();      } gradientdrawable.setcolor (BackColor);      }else {setbackgroundcolor (backColor);     }}}/** * Set button pressed color * @param backcolorselected */public void setbackcolorselected (int backcolorselected) {  This.backcolorselectedi = backcolorselected; }/** * Set button pressed color * @param backcolorselected */public void setbackcolorselected (String backcolorselected) {T  His.backcolorselecteds = backcolorselected; }/** * Set the background image of the button * @parAM BackgroundImage */public void setbackgroundimage (int backgroundimage) {this.backgroundimage = backgroundimage;    if (backgroundimage! = 0) {setbackgroundresource (backgroundimage); }}/** * Set button pressed background image * @param backgroundimageseleted */public void setbackgroundimageseleted (int backgroundimage  seleted) {this.backgroundimageseleted = backgroundimageseleted;      }/** * Set button fillet radius size * @param radius */public void Setradius (float radius) {if (gradientdrawable = = null) {    gradientdrawable = new Gradientdrawable ();  } gradientdrawable.setcornerradius (RADIUS); }/** * Set button text color * @param textcolor */public void settextcolors (String textcolor) {this.textcolors = Textcolo    R  SetTextColor (Color.parsecolor (TextColor));    }/** * Set button text color * @param textcolor */public void Settextcolori (int textcolor) {This.textcolori = TextColor;  SetTextColor (TextColor); }/** * Set button pressed text color * @param textcolor */public void SetTextcolorselected (String textcolor) {this.textcolorseleteds = TextColor; }/** * Set button pressed text color * @param textcolor */public void settextcolorselected (int textcolor) {This.textcolorselet  EDI = TextColor;  }/** * Button shape * @param shape */public void setshape (int shape) {this.shape = shape; }/** * Sets whether it is rounded * @param fillet */@SuppressWarnings ("deprecation") public void Setfillet (Boolean fillet) {t    His.fillet = fillet;      if (fillet) {if (gradientdrawable = = null) {gradientdrawable = new gradientdrawable ();      }//gradientdrawable.rectangle Gradientdrawable.setshape (shape);      Gradientdrawable.setcornerradius (RADIUS);    Setbackgrounddrawable (gradientdrawable); }  }}

2 activity_buttonm.xml layout file, in order to demonstrate that the effect defines three empty linearlayout, the following will add child controls for each of them
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/ Res/android "android:layout_width=" match_parent "android:layout_height=" Match_parent "android:orientation=" Vertical "> <linearlayout android:id=" @+id/ll_button1 "android:layout_width=" Match_parent "android:layout  _height= "Wrap_content" android:layout_margintop= "30DP" android:orientation= "Horizontal" > </LinearLayout> <linearlayout android:id= "@+id/ll_button2" android:layout_width= "match_parent" android:layout_height= "Wrap_c Ontent "android:layout_margintop=" 30DP "android:orientation=" horizontal "> </LinearLayout> <linearlayou T android:id= "@+id/ll_button3" android:layout_width= "match_parent" android:layout_height= "Wrap_content" Andro id:layout_margintop= "30DP" android:orientation= "horizontal" > </LinearLayout></LinearLayout>

3 ButtonMActivity.java:ButtonM test class
Package Landptf.control;import Android.app.activity;import Android.graphics.color;import Android.graphics.drawable.gradientdrawable;import Android.os.bundle;import Android.view.view;import Android.view.view.onclicklistener;import Android.view.viewgroup.layoutparams;import android.widget.LinearLayout; Import android.widget.toast;/** * BUTTONM Test class * @author LANDPTF * @date 2015-6-8 */public class Buttonmactivity extends Act  ivity{//define three empty layouts to load the button control, only to demonstrate the effect, the actual development is not recommended to use the private linearlayout llButtonM1;  Private LinearLayout llButtonM2;  Private LinearLayout llButtonM3;  Definition of three buttonm array private buttonm[] buttonM1;  Private buttonm[] buttonM2;  Private buttonm[] buttonM3;  Define two sets of color values, press and hold the button background color private static final string[] ColorList = {"#7067E2", "#FF618F", "#B674D2", "#00C2EB"};  private static final string[] Colorselectedlist = {"#3C3779", "#88354C", "#613E70", "#00677D"};    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); SetcontentviEW (R.LAYOUT.ACTIVITY_BUTTONM);  Initview ();    }//Initialize control private void Initview () {//Instantiate layout control llButtonM1 = (linearlayout) Findviewbyid (R.id.ll_button1);    LlButtonM2 = (linearlayout) Findviewbyid (R.id.ll_button2);    LlButtonM3 = (linearlayout) Findviewbyid (R.id.ll_button3);    Instantiates an array of controls, each of which defines 4 buttonM1 = new Buttonm[4];    buttonM2 = new Buttonm[4];    ButtonM3 = new Buttonm[4]; Gets the width of the screen, four buttons per line, 60 total 300, except 4 for each control's width @SuppressWarnings ("deprecation") int btnwidth = (Getwindowmanager (). getde    Faultdisplay (). GetWidth ()-300)/4;    Define the first layout of Linearlayout.layoutparams LP1;      for (int i = 0; i < 4; i++) {//Set style for buttonM1, right angle rectangle buttonm1[i] = new Buttonm (this);      Font Color Buttonm1[i].settextcolori (Android.graphics.Color.WHITE);      Font size buttonm1[i].settextsize (14);      Background color Buttonm1[i].setbackcolor (Color.parsecolor (Colorlist[i]));      Selected background color buttonm1[i].setbackcolorselected (Color.parsecolor (Colorselectedlist[i]));  Text hints    Buttonm1[i].settext ("TEXT" + i);      The value of the set ID here is I, otherwise the onclick V.getid () will always be-1 buttonm1[i].setid (i);      Defines the layout of the buttonM1, the width is adaptive, the height is 0.6 times times the width, the weight is 1//can also be written as LP1 = new Linearlayout.layoutparams (btnwidth, (int) (Btnwidth * 0.6));      LP1 = new Linearlayout.layoutparams (layoutparams.wrap_content, (int) (Btnwidth * 0.6), 1.0f);      The distance of the control from its right control, which is Lp1.setmargins (0,0,60,0);      Buttonm1[i].setlayoutparams (LP1); Set ButtonM1 Click event Buttonm1[i].setonclicklistener (New Onclicklistener () {@Override public void OnClick (        View v) {toast.maketext (Buttonmactivity.this, "You have selected" + v.getid () + "X", Toast.length_short). Show ();      }      });      Set Paddingleft to Llbuttonm1.setpadding (60, 0, 0, 0);    Add buttonM1 to LlButtonM1 Llbuttonm1.addview (Buttonm1[i]);    }//define a second layout linearlayout.layoutparams LP2;      for (int i = 0; i < 4; i++) {//Set style for buttonM2, rounded rectangle buttonm2[i] = new Buttonm (this); Buttonm2[i].settextcolori (Android.graphics.Color.WHITE);      Buttonm2[i].settextsize (14);      Sets whether rounded corners are buttonm2[i].setfillet (true);      Sets the radius size of the fillet Buttonm2[i].setradius (18);      Buttonm2[i].setbackcolor (Color.parsecolor (colorlist[i));      Buttonm2[i].setbackcolorselected (Color.parsecolor (colorselectedlist[i));      Buttonm2[i].settext ("TEXT" + i);      Buttonm2[i].setid (i);      LP2 = new Linearlayout.layoutparams (layoutparams.wrap_content, (int) (Btnwidth * 0.6), 1.0f);      Lp2.setmargins (0,0,60,0);      Buttonm2[i].setlayoutparams (LP2); Buttonm2[i].setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {Toas        T.maketext (Buttonmactivity.this, "You have selected" + v.getid () + "X", Toast.length_short). Show ();      }      });      Llbuttonm2.setpadding (60, 0, 0, 0);    Llbuttonm2.addview (Buttonm2[i]);    }//define a third layout linearlayout.layoutparams lp3; for (int i = 0; i < 4; i++) {//Set style for buttonM3, round buttonm3[i] = new Buttonm (this);     Buttonm3[i].settextcolori (Android.graphics.Color.WHITE);      Buttonm3[i].settextsize (14);      Set to circle, default to Rectangle, Gradientdrawable.rectangle buttonm3[i].setshape (gradientdrawable.oval);      Buttonm3[i].setfillet (TRUE);      Buttonm3[i].setbackcolor (Color.parsecolor (colorlist[i));      Buttonm3[i].setbackcolorselected (Color.parsecolor (colorselectedlist[i));      Buttonm3[i].settext ("TEXT" + i);      Buttonm3[i].setid (i);      LP3 = new Linearlayout.layoutparams (btnwidth,btnwidth);      Lp3.setmargins (0,0,60,0);      Buttonm3[i].setlayoutparams (LP3); Buttonm3[i].setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {Toas        T.maketext (Buttonmactivity.this, "You have selected" + v.getid () + "X", Toast.length_short). Show ();      }      });      Llbuttonm3.setpadding (60, 0, 0, 0);    Llbuttonm3.addview (Buttonm3[i]); }  }}

The notes basically explain that you can slowly accumulate these controls and eventually form a library of your own, perfect in different projects, making them more powerful.

I'll introduce you to you tomorrow. By inheriting relativelayout, implementing multiple controls, allowing different projects to be applied, avoiding rewriting every time

Android custom controls, setting the button's style dynamically

Related Article

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.