1. Writing the main class
Package Com.sample.button;import Android.content.context;import Android.content.res.typedarray;import Android.graphics.drawable.drawable;import Android.util.attributeset;import Android.util.log;import Android.widget.compoundbutton;import Com.example.buttonsample.r;public class MyButton extends Compoundbutton {public MyButton (context context, AttributeSet attrs, int defstyle) {Super (context, attrs, Defstyle);} Private drawable imgoff;private drawable imgon;public MyButton (context context, AttributeSet Attrs) {Super (context, ATTRS); TypedArray a = Context.gettheme (). Obtainstyledattributes (Attrs, R.styleable.mybutton, 0, 0); try {Imgoff = a.getdrawable (r.styleable.mybutton_imgoff); Imgon = A.getdrawable (R.styleable.mybutton_imgon);} catch (Exception e) {e.printstacktrace ();} A.recycle ();} Public MyButton (Context context) {super (context);} @Overridepublic void Setchecked (Boolean checked) {super.setchecked (checked); udpatedrawable ();} private void Udpatedrawable () {if (this.ischecked ()) {LOG.E (mybutTon.class.getName (), "Changing to Imgon"); this.setbackgrounddrawable (Imgon);} else {LOG.E (MyButton.class.getName (), "Changing to Imgoff"); this.setbackgrounddrawable (Imgoff);}} @Overrideprotected void Onfinishinflate () {udpatedrawable (); Super.onfinishinflate ();}}
2. Writing the attrs definition file (res/values/attrs.xml)
<?xml version= "1.0" encoding= "Utf-8"?><resources> <declare-styleable name= "MyButton" > <attr name= "Imgon" format= "reference"/> <attr name= "Imgoff" format= "reference"/> </ Declare-styleable> </resources>
3. The 2 picture resources involved are as follows
Res/drawable/off.png
Res/drawable/on.png
4. layout file for test activity
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android " xmlns:app=" Http://schemas.android.com/apk/res/com.example.buttonsample " android:layout_width= "Match_parent" android:layout_height= "match_parent" android:orientation= "vertical" > < Com.sample.button.MyButton android:id= "@+id/testmy" android:layout_width= "Wrap_content" android: layout_height= "Wrap_content" android:background= "@android: Color/white" app:imgoff= "@drawable/off" app:imgon= "@drawable/on" > </com.sample.button.MyButton></LinearLayout>
5. The actual effect is:
When you click the button, the button switches between the following 2 images.
A simple Android Custom view (Switch Button for API < 14)