Android Development Advanced custom Control sliding switch Implementation "with demo source download" _android

Source: Internet
Author: User
Tags set background sqlite database

This article describes the implementation of the sliding switch for Android advanced custom control. Share to everyone for your reference, specific as follows:

Custom switch controls

Android custom controls typically have three different ways

1, inherit the inherent Android control, on the basis of Android native control, to add functionality and logic.

2, Inherit viewgroup, this kind of custom control can add other child controls to own layout inside.

3, inherit view, such a custom control does not have too much resemblance to the native control, nor does it need to add other child controls to its own belly.

Toggleview Custom Switch control representations do not have anything similar to the Android native controls and do not follow the Android native place in the sliding effect, so our custom Toggleview chooses to inherit view

The same custom control requires a three-way replication of the construction method

The constructor is invoked when the control is used in the layout, and when there is an additional style attribute, public
toggleview (context context, AttributeSet attrs, int defstyle); //When the
control is used in the layout, the constructor is called Public
toggleview (context context, AttributeSet attrs)
//When the control is directly new in Java code, Invoke the constructor method public
Toggleview

Because it's a custom control, it's better to have the properties defined by yourself. We define three attributes here

1. Background picture
2, the picture of the slider
3, the layout of the default switch state

So you need to use custom attributes.

In the values directory, create a new XML file, Attrs.xml

Define your own attributes inside

<?xml version= "1.0" encoding= "Utf-8"?>
<resources>
 <declare-styleable name= "Toggle" >
  <attr name= "Switchbackground" format= "reference"/> <attr name= "Slidingbackground"
  Reference "/> <attr name= togglestate" format= "
  boolean"/>
 </declare-styleable>
</ Resources>

<declare-styleable Name property > is the name of the property that can be found in the R file.

<attr> tags, a label to write a property Name property represents the property names, and format represents the property type

Three property names and attribute types are defined here.

Property and the three constructed methods of the custom control are complete, so that we can add the custom controls to the layout file.

<relativelayout
 xmlns:android= "http://schemas.android.com/apk/res/android"
 xmlns:hss= "http:// Schemas.android.com/apk/res/com.hss.toggle "
 android:layout_width=" match_parent "
 android:layout_height= "Match_parent"
 >
 <com.hss.toggle.toggleview
 android:id= "@+id/toggleview"
 android:layout_ height= "Wrap_content"
 android:layout_width= "wrap_content"
 android:layout_centerinparent= "true"
 hss:switchbackground= "@drawable/switch_background"
 hss:slidingbackground= "@drawable/slide_button_ Background "
 hss:togglestate=" true "
 >
 </com.hss.toggle.ToggleView>
</ Relativelayout>

Note: in my custom control Com.hss.toggle.ToggleView, some of the properties start with Android, and some of the properties start with HSS (my own defined namespace).

Take a look at the second line of this piece of code,

Xmlns:hss= "Http://schemas.android.com/apk/res/com.hss.toggle"

I'm writing a code here that says that by importing every item in the Values/attrs.xml, you can use my attributes directly in Attrs.xml.

After you can use a custom attribute directly, the question should focus on how to get the value of my custom attribute in Java code.

Gets from the name value of the namespace and custom attributes, looking at the code:

String namespace = "Http://schemas.android.com/apk/res/com.hss.toggle";
int toggle_switchbackground = Attrs.getattributeresourcevalue (namespace, "Switchbackground",-1);
int toggle_slidingbackground = Attrs.getattributeresourcevalue (namespace, "Slidingbackground",-1);
Toggle_state = Attrs.getattributebooleanvalue (namespace, "Togglestate", false);

Did you see that? This method uses the attr parameter, so the operation obtained from defining the value of the attribute should be executed within two parameters.

The class of the custom control as a whole is shown in code:

Package com.hss.toggle;
Import Android.content.Context;
Import Android.graphics.Bitmap;
Import Android.graphics.BitmapFactory;
Import Android.graphics.Canvas;
Import Android.util.AttributeSet;
Import Android.util.Log;
Import android.view.MotionEvent;
Import Android.view.View;
 /** * Custom Switch control * @author HSS/public class Toggleview extends View {private static final String TAG = "Toogleview";
 Private Bitmap Sliding_background;
 Private Bitmap Switch_background;
 Private Boolean issliding = false;
 Private Boolean toggle_state = false;
 private int downx;
 Private Mtogglestatechangelistener; Constructs the method, when the XML file layout, specifies the style when the call public Toggleview (the context, AttributeSet attrs, int defstyle) {Super (context,
 Attrs, Defstyle); 
 }//constructor method, when layout in an XML file, call public Toggleview when no style is specified (context, AttributeSet attrs) {This (context, attrs, 0);
 Gets the value of the custom attribute in the XML in Java code String namespace = "Http://schemas.android.com/apk/res/com.hss.toggle"; int toggle_switchbackground = Attrs.getattributeresourcevalue (namespace, "Switchbackground",-1);
 int toggle_slidingbackground = Attrs.getattributeresourcevalue (namespace, "Slidingbackground",-1);
 Toggle_state = Attrs.getattributebooleanvalue (namespace, "Togglestate", false);
 LOG.I (TAG, "+toggle_slidingbackground+" "+toggle_switchbackground");
 Set the custom switch picture settoggleswitchbackground (toggle_switchbackground);
 Settoggleslidingbackground (Toggle_slidingbackground);
 Settogglestate (toggle_state);
 }//Construction method calls the public Toggleview (context, NULL) when new in code; /** * Set background picture for sliding control * * @param toggle_slidingbackground picture ID/private void settoggleslidingbackground (int toggle_
 Slidingbackground) {sliding_background = Bitmapfactory.decoderesource (Getresources (), toggle_slidingbackground); /** * Give background control, set background picture * * @param toggle_switchbackground picture ID/private void settoggleswitchbackground (int toggle_s Witchbackground) {switch_background = Bitmapfactory.decoderesource (getresources(), toggle_switchbackground); @Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {//measure the size of the control, set the size of the control to the size of the background picture Setmeasu
 Reddimension (Switch_background.getwidth (), Switch_background.getheight ());  @Override protected void OnDraw (Canvas Canvas) {//Start drawing custom controls, using the Canvas object to first draw the background picture Canvas.drawbitmap (Switch_background,
 0, 0, NULL); if (issliding) {//If it is a sliding state//the relative distance from the left of the control is: (The x-axis distance from the focus at the top left of the control at all times)-(The x-axis width of the control itself half) int left = Downx-sliding_backgroun
  D.getwidth ()/2; The maximum sliding distance of the control (the maximum distance from the left) is: (width of the background picture)-(width of the slider picture) int rightalign = Switch_background.getwidth ()-Sliding_
  Background.getwidth ();
  If the distance to the left is less than 0, he is not allowed to move to the left if (leave < 0) {left = 0;
  else if (Left > RightAlign) {//If the distance from the left-hand side should be the maximum distance from the left, and not let him move to the right side = rightalign;
 }//Control of the property can be followed by the painting of Canvas.drawbitmap (Sliding_background, left, 0, NULL); else {//If not sliding, draw the position of the slider according to the state of the switch in the control's properties if (toggle_state) {//If the switch state is true, the slider moves to the rightmost int left = Switch_background.getwi Dth)-Sliding_background.getwidth ();
  Canvas.drawbitmap (Sliding_background, left, 0, NULL);
  else {//If the switch state is false, the slider moves to the leftmost canvas.drawbitmap (sliding_background, 0, 0, NULL);
 } super.ondraw (canvas);
 @Override public boolean ontouchevent (Motionevent event) {//rewrite touch event int action = Event.getaction ();
  Switch (action) {case Motionevent.action_down://start clicking, whether sliding to true, get to the current finger distance issliding = true;
  DOWNX = (int) event.getx ();
 Break
  Case MotionEvent.ACTION_MOVE:downX = (int) event.getx ();
 Break
  Case MOTIONEVENT.ACTION_UP:///////When the click is finished, it will be recorded as false to obtain the coordinate DOWNX = (int) event.getx () of the moving x axis;
  Issliding = false;
  Gets the value in the middle of the background picture int center = switch_background.getwidth ()/2;
  Boolean state = downx > center;
  If the state of succession is not the same, the new state is assigned to the member variable, and then the listening method is invoked if (Toggle_state!= states) {toggle_state =;
  if (null!= mtogglestatechangelistener) {mtogglestatechangelistener. Ontogglestate (toggle_state);
 }} break;
 //Call once OnDraw () method invalidate (); RetuRN true;
 ///Set the Listener method to the custom switch control public void Setontogglestatelinstener (Ontogglestatechangelistener listen) {
 Mtogglestatechangelistener = listen;
 } public void Settogglestate (Boolean b) {toggle_state = b;
 }//Listener callback interface, which implements the public interface Ontogglestatechangelistener {public void Ontogglestate (Boolean) by the class implementing the interface;

 }
}

So, the logic of our custom Control section is written, and it's mainactivity to call

Package com.hss.toggle;
Import android.app.Activity;
Import Android.os.Bundle;
Import Com.hss.toggle.ToggleView.OnToggleStateChangeListener;
Import Com.hss.toggle.utils.ToastUtil;
public class Mainactivity extends activity{
 private Toggleview Toggleview;
 @Override
 protected void onCreate (Bundle savedinstancestate) {
 //TODO auto-generated method stub
 Super.oncreate (savedinstancestate);
 Setcontentview (r.layout.activity_main);
 Toggleview = (Toggleview) Findviewbyid (R.id.toggleview);
 Toggleview.setontogglestatelinstener (New Ontogglestatechangelistener () {
  @Override public
  Void Ontogglestate (Boolean state) {
  showtoast (state);
  }
 );
 Here we call a quick-play Toast tool class
 private void Showtoast (Boolean state) {
 toastutil.makesuddenlytoast ( Getapplicationcontext (), state? " Open ": Off");
 }


The Toastutil classes are as follows:

Package com.hss.toggle.utils;
Import Android.content.Context;
Import Android.widget.Toast;
/**
 * @title Toast Tool class
 * @author HSS
/public class Toastutil {
 private static Toast Toast;
 /**
 * Pop-up short time toast
 * @param context Object
 * @param text to pop up * *
 public
 static void Makeshorttoast (context context,string text) {
 toast = toast.maketext (context, text, toast.length_short);
 Toast.show ();
 }
 /**
 * pops up long toast
 * @param context Object
 * @param text to pop up * * public
 static void Makelongtoast (context context,string text) {
 toast = toast.maketext (context, text, toast.length_long);
 Toast.show ();
 }
 /**
 * Single case Toast
 * @param context Object
 * @param text to pop up * *
 public
 static void Makesuddenlytoast (context context,string text) {
 if (toast==null) {
  toast = toast.maketext (context, text, Toast.length_short);
 }
 Toast.settext (text);
 Toast.show ();
 }


To summarize, in fact, the steps for this custom control are as follows:

1, the data type of the custom attribute and attribute value in Values/attrs.xml

2. Define custom control classes in Java code, inherit view or ViewGroup or Android native controls, implement construction methods, get the values of custom attributes, and write corresponding logic and click events.

3. Use custom controls and custom attributes (note namespaces) in layout files.

4. Calling in Mainactivity

Full Instance code click here Download the site .

More interested readers of Android-related content can view the site: "Summary of Android Control usage", "Android View Summary", "Android operation SQLite Database Skills Summary", " Android operation JSON format data tips summary, "Android Database Operation skills Summary", "Android File Operation skills Summary", "Android programming development of the SD card operation Summary", "Android Development introduction and Advanced course" and " Android Resource Operating Skills summary

I hope this article will help you with the Android program.

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.