Android Custom Control Case Rollup 2 (custom switch, drop down refresh, sideslip menu) _android

Source: Internet
Author: User
Tags abs gety xmlns

Case four custom switches:

Function Introduction: The function of this case is to create a custom switch, you can decide the background of the switch. When the slide switch, the slider of the switch can follow the finger to move. When the finger is released, the slider slides to the right or to the far left, depending on the state of the switch, while saving the state of the switch, and then callback the state of the switch to the caller. Of course, the switch control given by the above functional system can also be implemented.

Implementation steps:

1. Write a class to inherit view, rewrite the two parameters of the construction method. Specify the workspace in the constructor method to associate the property values in the Java code with the attribute values in the XML by using the Attrs.getattributeresourcevalue method. This allows you to specify the associated property values in the XML file. Rewrite the onmeasure and OnDraw methods to draw pictures. This measure the size of the picture directly using the Setmeasureddimension method, get the size of the picture itself.
2. Set the interface callback. For the picture, we want to be able to get the state of the switch in the caller, so we need to set an interface callback to monitor the state of the switch when the state of the switch is changed time to call. The advantage of an interface callback is that the caller does not know when to invoke it, so set an interface in another file to trigger the event in that file. Because the method of the interface is overridden, the overridden method is executed. This allows you to implement a callback to the data. The application of the interface callback in the custom control is more extensive, and almost all of the controls need to be set up for listening, and the writing is more fixed.
3. Rewrite the Ontouchevent () method. Analysis that the switch consists of two parts, part of the base, part of the film and. When the fingers slide, the slices should follow the fingers. When the left side of the paddle is less than the left side of the base, let the coordinates and base of the left side of the film align, when the right side of the stroke is larger than the right coordinate of the base, so that the coordinates of the right side of the slice and the base are aligned, so as to ensure that When the finger is released, determine whether the centerline coordinates of the slice are on the left or right side of the center line of the base, in order to decide whether the film will eventually stop on the left or right. The state of the switch is changed at the same time, the state of the switch is recalled to the call of the control, and the state of the switch is read.

Code implementation. Code in the main program (caller):

Package com.example.aswitch;

Import Android.os.Bundle;
Import Android.widget.Toast;

public class Mainactivity extends Appcompatactivity {

  private Mytogglebutton ToggleButton;

  protected void onCreate (Bundle savedinstancestate) {
    super.oncreate (savedinstancestate);
    Setcontentview (r.layout.activity_main);
    ToggleButton = (Mytogglebutton) Findviewbyid (;
    Togglebutton.setonstatechangedlistener (New Mytogglebutton.onstatechangedlistener () {
      public void Onstatechanged (Boolean state) {
        Toast.maketext (mainactivity.this, state?) "On": "Off", Toast.length_short). Show ();}}

The realization of the custom switch;

Package com.example.aswitch;
Import Android.content.Context;
Import Android.util.AttributeSet;
Import android.view.MotionEvent;

Import Android.view.View;
 /** * Created by Huang on 2016/12/1.
  * * public class Mytogglebutton extends View {private Bitmap background;
  Private Bitmap Slideicon;
  Private Boolean state;
  Private Onstatechangedlistener Monstatechangedlistener;
  private int backgroundwidth;
  private int backgroundheight;
  private int slideiconwidth;
  private int slideiconheight;
  private int slideiconleft;

  private int maxslideiconleft;
    Public Mytogglebutton (context, AttributeSet attrs) {Super (context, attrs);
    String namespace = "Http://";
    int slidebackgroundresid = Attrs.getattributeresourcevalue (namespace, "Slidebackground",-1); int slideiconresid = Attrs.getattributeresourcevalue (namespace, "SlideiCon ",-1); if (Slidebackgroundresid!=-1 && slideiconresid!=-1) {setswitchimage (Slidebackgroundresid, Slideiconresi
    Boolean state = Attrs.getattributebooleanvalue (namespace, ' state ', false);
  SetState (state); /** * Set Switch picture * @param slidebackgroundresid switch background image resource ID * @param slideiconresid switch above the slider icon/public V OID setswitchimage (int slidebackgroundresid, int slideiconresid) {background = Bitmapfactory.decoderesource (getResour
    CES (), slidebackgroundresid);

    Slideicon = Bitmapfactory.decoderesource (Getresources (), slideiconresid);
    Backgroundwidth = Background.getwidth ();
    Backgroundheight = Background.getheight ();
    Slideiconwidth = Slideicon.getwidth ();

    Slideiconheight = Slideicon.getheight ();
  Maxslideiconleft = Backgroundwidth-slideiconwidth;
    /** set the status of the switch button/public void SetState (Boolean state) {checkstate);
    if (state) {slideiconleft = Maxslideiconleft;
  } else {    Slideiconleft = 0; }} public void Setonstatechangedlistener (Onstatechangedlistener monstatechangedlistener) {This.monstatechangedl
  Istener = Monstatechangedlistener;
  /** Switch button state Change listener */public interface Onstatechangedlistener {void onstatechanged (Boolean);
    /** * Method of measuring View * * @Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {
  Setmeasureddimension (Backgroundwidth, backgroundheight);
    /** the View drawing method * @param Canvas Canvas * * */@Override protected void OnDraw (canvas canvas) {int left = 0;
    int top = 0;

    Canvas.drawbitmap (background, left, top, null);
  Canvas.drawbitmap (Slideicon, slideiconleft, 0, NULL); @Override public boolean ontouchevent (Motionevent event) {switch (event.getaction ()) {case Motionevent.

        Action_down:case MotionEvent.ACTION_MOVE:slideIconLeft = (int) (EVENT.GETX ()-SLIDEICONWIDTH/2); if (Slideiconleft < 0) {slideiconleft = 0;
        else if (Slideiconleft > Maxslideiconleft) {slideiconleft = Maxslideiconleft;
      } break;
          Case MotionEvent.ACTION_UP:if (Event.getx () < BACKGROUNDWIDTH/2) {slideiconleft = 0;
        CheckState (FALSE);
          else {slideiconleft = Maxslideiconleft;
        CheckState (TRUE);
    } break;
    } invalidate ();
  return true;

      private void CheckState (Boolean state) {if (This.state-!= state) {this.state = state;
      if (Monstatechangedlistener!= null) {monstatechangedlistener.onstatechanged (state);


Authoring of layout files:

<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android=
"" /res/android "
  xmlns:huang=" Http:// "
  android:layout_width=" match_parent "
  android:layout_height=" match_parent ">

    android:id=" @+id /toggle_button "
    android:layout_width=" wrap_content "
    android:layout_height=" Wrap_content "
    Huang: slidebackground= "@mipmap/slide_background2"
    huang:slideicon= "@mipmap/slide_icon2"
    huang:state= "false "/>


To make the properties in the layout file work, you also need to write a attrs.xml file separately in the values folder, declaring the related properties.

<?xml version= "1.0" encoding= "Utf-8"?>
  <declare-styleable name= "Mytogglebutton "> <attr name=" slidebackground "format=" reference "/> <attr name=
    " Slideicon "format=" Reference " />
    <attr name= "state" format= "boolean"/>

Case Five Drop-down refreshed listview:

Feature Description: The system itself is ListView by default without drop-and-pull loading more features. But ListView have Addheadview and Addfootview methods, so you can add a head layout or a foot layout for ListView. For the header layout, there are three states, Drop-down refresh, release refresh, is refreshing, accompanied by the corresponding animation to be prompted. After the refresh is successful, add a set of information for the ListView. After the same foot layout is loaded successfully, a message is loaded after the last piece of data in the ListView.

Implementation steps:

1. Write layout file. In addition to the need for a ListView in the main interface, you need a header layout file and a tail layout file. In the initial state, both the header layout and the foot layout are hidden. When the slide event starts, adjust the position of the head layout and the foot layout. Over here. Header layout and foot layout of the root table is best to use linearlayout for wrapping, otherwise the sliding display is prone to problems.

2. Write a class to inherit ListView. Initialize the interface layout, through the view.measure (0, 0) method to trigger the measurement, mesure internal will call onmeasure, so that the height of the head layout. As step one says, when the start state, the header layout is hidden, so set the Panding value for the header layout, so that the head layout is hidden, only the second parameter in Setpadding is set to the height of the negative header file. Similarly, the display header layout only needs to set the second parameter in the setpadding to 0. The same method is used for the display and concealment of the root layout. Of course, you can change the setpadding fourth parameter to control the display and hide.

3. Rewrite the Ontouchevent () method. When the finger is pressed, record the initial position. A y-coordinate is recorded when the finger slides. The direction of finger sliding is judged by the difference of two times coordinates. When the first object visible is position to 0, if the fingers slide down, there are two states, one is a drop-down refresh, refers to the head layout from not see just all visible, one is to release the refresh, the head layout is all visible after continue to drag down, will enter the release refresh state. There is also a state is refreshing, this state, the head layout just stay at the top, to maintain a period of time. In actual development, refreshing is requesting a network from the server. False data is added here. Transitions between different states are also accompanied by animation, so there is also a motion tween to achieve an upward and downward effect.

4. Write a sliding monitoring event, in the listening event for the layout logic of the script. When the following three situations are met, the foot layout is displayed, one ListView is idle, and the last item visible on the interface is the last item in ListView, and the other is that if you are not currently doing something that is loading more. When displaying the layout of the feet, not only do you want to set the padding value, but also select the last entry of ListView, so that you can display it completely on the interface.

5. The final note is that, whether it is the same layout, or the layout of the foot, you have to modify the state. So, you can add a callback listener. Indicates that the data is refreshed or loaded, and the header layout and the foot layout can be hidden, while the state of the header layout is restored to a drop-down refresh and the foot layout is not being loaded. At the same time, stop the related animation, modify the display status.

The writing of the main program (caller). The general refresh is the request database data, here directly gives the simulation data demonstration effect.

Package Com.example.pulltofreshlistview;
Import Android.os.Bundle;
Import Android.os.Handler;

Import Android.widget.ArrayAdapter;

Import Com.example.pulltofreshlistview.view.PullToRefreshListView;

Import java.util.ArrayList;
  public class Mainactivity extends Appcompatactivity {private Pulltorefreshlistview listView;
  Private arraylist&lt;string&gt; datas;

  Private arrayadapter&lt;string&gt; adapter;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);

    ListView = (Pulltorefreshlistview) Findviewbyid (;
    Datas = new arraylist&lt;string&gt; ();
    for (int i = 0; i &lt; i++) {Datas.add ("I found the money again, so happy ah ^_^ \ t" + i); } adapter = new Arrayadapter&lt;string&gt; (this, Android.
    R.layout.simple_list_item_1, datas);

    Listview.setadapter (adapter); Listview.setonrefreshinglistener (New PULLTOREFRESHLIstview.onrefreshinglistener () {@Override public void onrefreshing () {reloaddata ();
      @Override public void Onloadmore () {loadmore ();
    }); /** * Re-networking Access data */protected void Reloaddata () {new Handler (). postdelayed (New Runnable () {@Overri
        De public void Run () {datas.add (0, "I am the refreshed data");
        Adapter.notifydatasetchanged ();
      Listview.onrefreshcomplete ();
  }, 3000); 
      /** * Networking Load More data */protected void Loadmore () {new Handler (). postdelayed (New Runnable () {@Override
        public void Run () {Datas.add ("I am loading more data");
        Adapter.notifydatasetchanged ();
      Listview.onloadmorecomplete ();
  }, 3000);     


Pull down to refresh the logical part of the ListView

Package Com.example.pulltofreshlistview.view;
Import Android.content.Context;
Import Android.util.AttributeSet;
Import android.view.MotionEvent;
Import Android.view.View;
Import android.view.animation.RotateAnimation;
Import Android.widget.AbsListView;
Import Android.widget.ImageView;
Import Android.widget.ListView;
Import Android.widget.ProgressBar;

Import Android.widget.TextView;

 /** * Created by Huang on 2016/12/1.
  * * public class Pulltorefreshlistview extends ListView {private View headerview;
  private float DownY;
  private int headerviewheight;
  private static final int state_pull_to_refresh = 0;
  private static final int state_release_refresh = 1;
  private static final int state_refreshing = 2;  private int currentstate = State_pull_to_refresh;
  Default is Drop-down refresh status private ImageView Iv_arrow;
  Private ProgressBar Progress_bar;
  Private TextView tv_state;
  Private Rotateanimation Upanim;
Private Rotateanimation Downanim;  Private Onrefreshinglistener Monrefreshinglistener;
  Private View Footerview;
  private int footerviewheight;

  Private Boolean Loadingmore;
    Public Pulltorefreshlistview (context, AttributeSet attrs) {Super (context, attrs);
    Initheaderview ();
  Initfooterview ();
    private void Initheaderview () {Headerview = View.inflate (GetContext (), r.layout.header_view, NULL);
    Iv_arrow = (ImageView) Headerview.findviewbyid (;
    Progress_bar = (ProgressBar) Headerview.findviewbyid (;
    Showrefreshingprogressbar (FALSE);
    Tv_state = (TextView) Headerview.findviewbyid (;
    Headerview.measure (0, 0);
    Headerviewheight = Headerview.getmeasuredheight ();
    Hideheaderview ();
    Super.addheaderview (Headerview);
    Upanim = Createrotateanim (0f, -180f);
  Downanim = Createrotateanim ( -180f, -360f);
    private void Initfooterview () {Footerview = View.inflate (GetContext (), r.layout.footer_view, NULL); FooteRview.measure (0, 0);
    Footerviewheight = Footerview.getmeasuredheight ();
    Hidefooterview ();

    Super.addfooterview (Footerview); Super.setonscrolllistener (New Onscrolllistener () {@Override public void onscrollstatechanged (Abslistview vie W, int scrollstate) {if (scrollstate = = Onscrolllistener.scroll_state_idle &amp;&amp; getlastvisiblep
          Osition () = = GetCount ()-1 &amp;&amp; Loadingmore = = False) {Loadingmore = true;
          Showfooterview ();

          SetSelection (GetCount ()-1);
          if (Monrefreshinglistener!= null) {Monrefreshinglistener.onloadmore (); @Override public void Onscroll (Abslistview view, int firstvisibleitem, int visibleitemcou
  NT, int totalitemcount) {}});
    private void Hidefooterview () {int paddingtop =-footerviewheight;
  Setfooterviewpaddingtop (paddingtop);
private void Showfooterview () {    int paddingtop = 0;
  Setfooterviewpaddingtop (paddingtop);
  } private void Setfooterviewpaddingtop (int paddingtop) {footerview.setpadding (0, paddingtop, 0, 0); /** * Set the loop to show progress * * @param showprogressbar If true, display ProgressBar, otherwise the arrow/private void Showrefreshi Ngprogressbar (Boolean Showprogressbar) {progress_bar.setvisibility (Showprogressbar?)
    View.VISIBLE:View.GONE); Iv_arrow.setvisibility (!showprogressbar?)

    View.VISIBLE:View.GONE);  if (Showprogressbar) {iv_arrow.clearanimation ();
   Animated view to clear the animation to really hide}/** * Create a rotational animation * * @param fromdegrees from which angle to turn * @param todegrees to which angle * @return * * Private rotateanimation Createrotateanim (float fromdegrees, float todegrees) {int pivotxtype = Ro
    int pivotytype = rotateanimation.relative_to_self;
    float pivotxvalue = 0.5f;
    float pivotyvalue = 0.5f; Rotateanimation ra = new Rotateanimation (Fromdegrees,Todegrees, Pivotxtype, Pivotxvalue, Pivotytype, Pivotyvalue);
    Ra.setduration (300);
    Ra.setfillafter (TRUE);
  return RA;
    }/** * Hidden Headerview/private void Hideheaderview () {int paddingtop =-headerviewheight;
  Setheaderviewpaddingtop (paddingtop);
    /** * Display Headerview/private void Showheaderview () {int paddingtop = 0;
  Setheaderviewpaddingtop (paddingtop); /** * Set Headerview paddingtop * * @param paddingtop * * private void setheaderviewpaddingtop (int padding
  Top) {headerview.setpadding (0, paddingtop, 0, 0); @Override public boolean ontouchevent (motionevent ev) {switch (ev.getaction ()) {case Motionevent.action
        _down:downy = Ev.gety ();
        Case MotionEvent.ACTION_MOVE:if (CurrentState = = state_refreshing) {return super.ontouchevent (EV);    int fingermovedistancey = (int) (Ev.gety ()-DownY); The distance of the finger movement if (fingermovediStancey &gt; 0 &amp;&amp; getfirstvisibleposition () = = 0) {int paddingtop =-headerviewheight + Fingermovedista

          Setheaderviewpaddingtop (paddingtop); if (Paddingtop &lt; 0 &amp;&amp; currentstate!= state_pull_to_refresh) {currentstate = State_pull_to_refresh
            Tv_state.settext ("Drop-down refresh");
            Iv_arrow.startanimation (Downanim);
          Showrefreshingprogressbar (FALSE); else if (paddingtop &gt;= 0 &amp;&amp; currentstate!= state_release_refresh) {currentstate = State_release
            Tv_state.settext ("loosen refresh");
            Iv_arrow.startanimation (Upanim);

          Showrefreshingprogressbar (FALSE);
        return true;
      } break; Case MotionEvent.ACTION_UP:if (CurrentState = = State_release_refresh) {currentstate = state_refreshing
          Tv_state.settext ("refreshing");
          Showrefreshingprogressbar (TRUE); ShowheadErview ();
          if (Monrefreshinglistener!= null) {monrefreshinglistener.onrefreshing ();
        } else if (CurrentState = State_pull_to_refresh) {Hideheaderview ();
    } break;
  return super.ontouchevent (EV); } public void Setonrefreshinglistener (Onrefreshinglistener monrefreshinglistener) {This.monrefreshinglistener = MO

    /** * ListView Refreshed Listener/public interface Onrefreshinglistener {void onrefreshing ();
  void Onloadmore ();
    /** * Network Refresh Data operation has been completed * * public void Onrefreshcomplete () {Hideheaderview ();
    CurrentState = State_pull_to_refresh;
  Showrefreshingprogressbar (FALSE);
    /** * The operation of loading more new data has been completed */public void Onloadmorecomplete () {Hidefooterview ();
  Loadingmore = false;


The layout file contains three parts, the ListView body part:

<?xml version= "1.0" encoding= "Utf-8"?> <relativelayout xmlns:android=
"" /res/android "
  xmlns:tools=" Http:// "
  android:layout_width=" Match_parent
  " android:layout_height= "Match_parent"
  tools:context= ". Mainactivity ">

    android:id=" @+id/list _view "
    android:layout_width=" match_parent "
    android:layout_height=" match_parent "/>

</ Relativelayout>

Header layout:

&lt;?xml version= "1.0" encoding= "Utf-8"?&gt; &lt;linearlayout xmlns:android= "" Android "Android:layout_width=" Match_parent "android:layout_height=" wrap_content "android:orientation=" Horizontal "android:gravity=" center_vertical "&gt; &lt;relativelayout android:layout_width=" 50DP "android:layout_height = "50DP" &gt; &lt;imageview android:id= "@+id/iv_arrow" android:layout_width= "Wrap_content" Android:la yout_height= "Wrap_content" android:src= "@mipmap/arrow" android:layout_centerinparent= "true"/&gt; &lt;Prog Ressbar android:id= "@+id/progress_bar" style= "@android: Style/widget.progressbar" Android:indeterminatedr awable= "@drawable/progress_medium_red" android:layout_width= "28DP" android:layout_height= "28DP" Android: Layout_centerinparent= "true" android:visibility= "Gone"/&gt; &lt;/RelativeLayout&gt; &lt;linearlayout Andro Id:layout_width= "Match_parent" android:layout_height= "wrap_content" android:gravity= "center" android:orientation= "vertical" &gt; &lt;textview
      Android:id= "@+id/tv_state" android:layout_width= "wrap_content" android:layout_height= "Wrap_content"
      Android:textcolor= "#FF0000" android:text= "Drop-down refresh"/&gt; &lt;textview android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:textcolor= "#666666" android:textsize= "12SP" Android:te

 xt= "Last Refresh time: 2015-07-25 19:59:39" android:layout_margintop= "4DP"/&gt; &lt;/LinearLayout&gt; &lt;/LinearLayout&gt;

Foot layout:

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"" Res/android "
  android:layout_width=" match_parent "
  android:layout_height=" Wrap_content "
  android: gravity= "center"
  android:orientation= "Horizontal" >

    style= "@android: style/ Widget.progressbar "
    android:layout_width=" 28DP "
    android:layout_height=" 28DP "
    android:layout_ Marginbottom= "8DP"
    android:layout_margintop= "8DP"
    android:indeterminatedrawable= "@drawable/progress_ Medium_red "/>

    android:layout_width=" wrap_content "android:layout_height=" Wrap_
    Content "
    android:layout_marginleft=" 6DP "
    android:text=" Loading more ... "
    android:textcolor=" #FF0000 " >


Case Six sideslip Menu:

Functional analysis: Most of the previous cases had only one control, so it was implemented by inheriting view. The Sideslip menu obviously requires two controls to be implemented, one for loading the main interface, and one for loading the Sideslip interface. So here we need to inherit viewgroup. Controls the display and concealment of the interface by sliding through the main interface.

Implementation steps:

1. The writing of the layout file. The layout file contains two parts, the main interface and the Sideslip interface. The main interface has a title bar, the title bar has a picture button, text composition. The picture can also control the display and hide of the sidebar by the Ox. The sidebar adds a linearlayout to the ScrollView and vertically arranges TextView display text in LinearLayout. Of course, the Sideslip menu can also be displayed with ListView, which is not used for simplicity ListView display. In addition, TextView need to set clickable to be true in order to respond to a click event.

2. Create a class that inherits from ViewGroup. Rewrite the Onmeasure () method to measure the size of the control, including two child controls. Here, the width of the Sideslip menu is written in the layout file and the interface of the main interface is wide fitting. So the Menu.measure (Menuwidth, Heightmeasurespec) and Main.measure (Widthmeasurespec, Heightmeasurespec) methods are called respectively to obtain. The child view in the typesetting container. Overriding the OnLayout () method is essential because the custom control contains more than one child view. The view is typeset, and the 0, 0 coordinates of the child view are the upper-left corner of the Slidingmenu. The Sideslip menu is typeset, the left coordinates of the menu are in the position of the negative menu, the top coordinate of the menu is 0, the right coordinate of the menu is at 0, and the bottom coordinate of the menu is at the bottom of the container. The main interface of the layout, the left coordinates of the main interface in 0 position, the main interface of the top coordinates at 0 position, the main interface of the right coordinates in the container's rightmost, the main interface of the bottom coordinates at the bottom of the container.

3. Rewrite onintercepttouchevent. This case is only concerned with horizontal strokes, so if the horizontal moving distance is larger than the vertical movement, it is considered to be horizontal movement, to intercept the event, not to let ScrollView use, this event is handled by the control itself. It is necessary to introduce the event distribution. The View collection is a Top-down process for distributing events. ViewGroup has the following 3 touch-related methods, dispatchtouchevent (Motionevent ev) for touch event issuance, onintercepttouchevent (motionevent ev) Used to intercept touch events, Ontouchevent (Motionevent event) is used to handle touch events. Onintercepttouchevent () is rewritten here, and the Ontouchevent () method is rewritten accordingly.

4. Implement the logic of sliding following in the Ontouchevent () method. In sliding events, only the lateral slide is concerned. When pressed, records the current x coordinate. When you slide, record the current x-coordinate again, subtracting the distance from the movement. Slide to the appropriate location through the Scrollto () method. The system-given Scrollto () method defaults to a negative to the right, so the overridable Scrollto () method guarantees that the move is positive. Code optimization. In fact, the above process can achieve the function of sideslip menu. When the sliding process is slightly blunt. You can then use Scroller, a class designed to simulate scrolling values. At the same time to cooperate with the Computescroll () method.

5. There is also a menu switch button, either open, or off. The Sideslip menu is fully displayed when opening. When off, hide the Sideslip menu. This logic is the same as the logic of the fingers raised in ontouchevent ().

Writing of the main program (caller):

Package com.example.slidingmenu;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.view.Window;
Import Android.widget.LinearLayout;
Import Android.widget.TextView;

Import Android.widget.Toast;
  public class Mainactivity extends activity {private Slidingmenu sliding_menu;
  Private LinearLayout Ll_menu;

  Private TextView tv_news;
    @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Requestwindowfeature (Window.feature_no_title);
    Setcontentview (R.layout.activity_main);
    Sliding_menu = (slidingmenu) Findviewbyid (;
    Ll_menu = (linearlayout) Findviewbyid (;
    Tv_news = (TextView) Findviewbyid (;
  Setcurrentselectedmenuitem (tv_news); /** Set the currently selected menu item */private void Setcurrentselectedmenuitem (View menuItem) {for (int i = 0; i &lt; Tchildcount ();
      i++) {View child = Ll_menu.getchildat (i); Child.setselected (Child = = MenuItem);
    A menu item in the/** menu list was clicked * * public void Onmenuitemclick (View v) {TextView TextView = (TextView) v;
    Toast.maketext (this, Textview.gettext (), Toast.length_short). Show ();
  Setcurrentselectedmenuitem (v);
  /** the menu button on the main interface clicked/public void Onmenutoggleclick (View v) {sliding_menu.toggle ();



The subject logic of the Sideslip menu.

Package com.example.slidingmenu;
Import Android.content.Context;
Import Android.util.AttributeSet;
Import android.view.MotionEvent;
Import Android.view.View;
Import Android.view.ViewGroup;

Import Android.widget.Scroller;
 /** * Created by Huang on 2016/12/1.
  * * public class Slidingmenu extends ViewGroup {private View menu;
  Private View main;
  private int menuwidth;
  private int downx;
  private int currentx;

  /** This class is specifically used to simulate scrolling numerical value * * Private scroller scroller;
    Public Slidingmenu (context, AttributeSet attrs) {Super (context, attrs);
  Scroller = new Scroller (context); @Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {super.onmeasure (widthmeasures  PEC, Heightmeasurespec); Measure the container's own wide-high menu = Getchildat (0); Gets the menu container main = Getchildat (1);   Gets the main interface container menuwidth = Menu.getlayoutparams (). width;

    Gets the menu's wide//Measurement menu menu.measure (menuwidth, Heightmeasurespec); Measurement of the main interface Main.measure (WidthmeasUrespec, Heightmeasurespec);
    @Override protected void OnLayout (Boolean changed, int l, int t, int r, int b) {int menuleft =-menuwidth;
    int menutop = 0;
    int menuright = 0;
    int menubottom = B-T;

    Menu.layout (Menuleft, Menutop, Menuright, Menubottom);
    int mainleft = 0;
    int maintop = 0;
    int mainright = r-l;
    int mainbottom = B-T;
  Main.layout (Mainleft, Maintop, Mainright, Mainbottom);
  /** * Let the interface scroll to the position of X, transfer positive to the right, transmit negative to left * @param x/public void Scrollto (int x) {super.scrollto (x, 0);
  /** get the current slide to position * * public int getmyscrollx () {return-super.getscrollx (); @Override public boolean onintercepttouchevent (motionevent ev) {switch (ev.getaction ()) {case Motioneve Nt.
        Action_down:downy = (int) ev.gety ();
        DOWNX = (int) ev.getx ();
        Case MotionEvent.ACTION_MOVE:int Distancex = Math.Abs ((int) (EV.GETX ()-downx)); int distancey = Math.Abs ((int) (Ev.gety ()-DownY));
        if (Distancex &gt; Distancey) {return true;
    } break;
  return super.onintercepttouchevent (EV); @Override public boolean ontouchevent (Motionevent event) {switch (event.getaction ()) {case Motionevent.
        ACTION_DOWN:DOWNX = (int) event.getx ();
        Case MotionEvent.ACTION_MOVE:int Fingermovedistancex = (int) event.getx ()-downx;

        int destx = CurrentX + Fingermovedistancex;
        if (Destx &lt; 0) {destx = 0;
        else if (Destx &gt; Menuwidth) {destx = Menuwidth;
        } scrollto (DESTX);
        Case MotionEvent.ACTION_UP:if (GETMYSCROLLX () &lt; MENUWIDTH/2) {startscroll (0);
        else {startscroll (menuwidth);
    } break;
  return true;
  int count;

  private int DownY; /** * Animate to a specified position * * @param destx where to slide (target position)/private VOID startscroll (int destx) {currentx = DESTX;
    int startx = GETMYSCROLLX ();
    int Distatncex = DESTX-STARTX;
    int duration = 800;
    Scroller.startscroll (startx, 0, Distatncex, 0, duration);
  Invalidate (); @Override public void Computescroll () {if (Scroller.computescrolloffset ()) {int Currx = Scroller.getcur
      RX ();
      Scrollto (CURRX);
      Invalidate ();
  } System.out.println ("Count =" + count);
    /** the Switch button on the menu, either on or off/public void toggle () {if (GETMYSCROLLX () &gt; 0) {startscroll (0);
    else {startscroll (menuwidth);


Overall layout

<?xml version= "1.0" encoding= "Utf-8"?> <com.example.slidingmenu.slidingmenu xmlns:android=
"http://" "
  android:id=" @+id/sliding_menu "
  android:layout_width=" match_parent "
  android:layout_height=" match_parent >

  <!--index in Slidingmenu 0-->
  <include layout= "@ Layout/menu "/>

  <!--index in Slidingmenu 1--> <include layout=
  " @layout/main "/>


Main interface Layout

&lt;?xml version= "1.0" encoding= "Utf-8"?&gt; &lt;linearlayout xmlns:android= "" Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:orientation=" "Vertical" &

  Gt &lt;linearlayout android:layout_width= "match_parent" android:layout_height= "Wrap_content"
      @mipmap/top_bar_bg "android:gravity=" center_vertical "android:orientation=" Horizontal "&gt; &lt;imageview 
      Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:onclick= "OnMenuToggleClick" android:src= "@mipmap/main_back"/&gt; &lt;view android:layout_width= "1DP" android:layout_height= "M Atch_parent "android:layout_marginbottom=" 6DP "android:layout_margintop=" 6DP "android:background=" @mipma P/top_bar_divider "/&gt; &lt;textview android:layout_width=" wrap_content "android:layout_height=" Wrap_con Tent "Android:layout_marginleft= "12DP" android:text= "News" android:textcolor= "@android: Color/white" android:textsize= "34sp"/&gt; 
    &lt;/LinearLayout&gt; &lt;textview android:layout_width= "match_parent" android:layout_height= "Match_parent" 

 android:gravity= "center" android:text= "for a small steamed bun, friendship Boat said turn over" android:textsize= "30sp"/&gt; &lt;/LinearLayout&gt;

Sideslip Interface Layout

&lt;?xml version= "1.0" encoding= "Utf-8"?&gt; &lt;scrollview xmlns:android= "" Android "Android:layout_width=" 240DP "android:layout_height=" match_parent "android:background=" @mipmap/menu_bg " &gt; &lt;linearlayout android:id= "@+id/ll_menu" android:layout_width= "240DP" android:layout_height= "Wrap_co"
      Ntent "android:orientation=" vertical &gt; &lt;textview android:id= "@+id/tv_news" android:text= "News" 
      style= "@style/menu_item" android:drawableleft= "@mipmap/tab_news"/&gt; &lt;textview android:text= "Subscriptions" style= "@style/menu_item" android:drawableleft= "@mipmap/tab_read"/&gt; &lt;textview " "Style=" @style/menu_item "android:drawableleft=" @mipmap/tab_local/&gt; &lt;textview = "posted" style= "@style/menu_item" android:drawableleft= "@mipmap/tab_ties"/&gt; &lt;textview android:te
 xt= "Picture" style= "@style/menu_item"     android:drawableleft= "@mipmap/tab_pics"/&gt; &lt;textview android:text= "topic" style= "@style/menu_item" android:drawableleft= "@mipmap/tab_ugc"/&gt; &lt;textview android:text= "vote" style= "@style/menu_item
  "Android:drawableleft=" @mipmap/tab_vote "/&gt; &lt;textview android:text=" aggregation reading style= "@style/menu_item"

 android:drawableleft= "@mipmap/tab_focus"/&gt; &lt;/LinearLayout&gt; &lt;/ScrollView&gt;

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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: 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.