Android: Hand-sliding layout viewgroup

Source: Internet
Author: User

Sliding with hand

Many developers are not familiar with the layout of the hand slide, here is an example, see a relativelayout slide display

Principle

Whether you are sliding with a hand or bouncing into a pop-up animation, you are essentially modifying the location of the view or ViewGroup, which is the Setx () sety () method.

    • Sliding with hand

Sliding with a hand means that when the user slides on the screen, a piece of layout slides as the finger slides. Therefore, the principle of its realization is to dynamically get the finger sliding distance in the Ontouch event, and then modify the view position.

    • Bounce Pop-up animation

Sliding with the hand, it is possible that the user only slide out of the view part of the Let go, in order to better effect, we follow the user's sliding direction, the view is displayed in the form of animation. So, its principle is to use valueanimator, dynamically modify the location of the view

Codexml layout

Our goal is to make the relativelayout with ID rl_left, slide out from the left side of the screen, or hide it on the left side of the screen.

<relativelayout  xmlns: Android  = "http://schemas.android.com/apk/res/android"  xmlns:tools  =" Http://schemas.android.com/tools " android:layout_width  = "match_parent"  android:layout_height  =" match_parent " android:background  =" @android: Color/white ";     <button  android:id  = "@+id/btn_1"  android:layout_width  =< Span class= "Hljs-value" > "wrap_content"  android:layout_height  = "wrap_content"  android:layout_alignparentend  =< Span class= "Hljs-value" > "true"  android:layout_alignparentright  = "true"  android:text  = " Show "/>     <button  android:id  = "@+id/btn_2"  android:layout_width  =< Span class= "Hljs-value" > "wrap_content"  android:layout_height  = "wrap_content"  android:layout_alignparentend  =< Span class= "Hljs-value" > "true"  android:layout_alignparentright  = "true"  android:layout_below  =" @id/btn_1 " android:text  =" Hide " />     <textview  android:id  = "@+id/tv_show"  android:layout_width  = "wrap_content"  android:layout_height  = "wrap_content"  android:layout_centerinparent  =< Span class= "Hljs-value" > "true" />     <relativelayoutandroid:id= "@+id/rl_left"android:layout_width="@ Dimen/rl_left_w "android:layout_height="match_parent "android:background=" # 00ff00 " >                                        <ListViewandroid:id="@+id/lv_test"android:layout_width= "Match_parent" android:layout_height="match_parent" />                                        </relativelayout></relativelayout>
mianactivity-Sliding and animation control focuses on the following methods:
    • Slidetoshow
    • Slidetohide
    • OnTouch
 PackageCom.example.net.mobctrl.ottotest;ImportJava.util.ArrayList;ImportJava.util.List;ImportAndroid.animation.ValueAnimator;ImportAndroid.animation.ValueAnimator.AnimatorUpdateListener;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.view.MotionEvent;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.view.animation.DecelerateInterpolator;ImportAndroid.widget.AdapterView;ImportAndroid.widget.AdapterView.OnItemClickListener;ImportAndroid.widget.ArrayAdapter;ImportAndroid.widget.ListView;ImportAndroid.widget.RelativeLayout;ImportAndroid.widget.TextView;/** * * @author Zheng Haibo * * * Public  class mainactivity extends Activity {    PrivateRelativelayout Rl_left;PrivateListView ListView;PrivateTextView tvShow;Private intRlwidth;//width of layout    Private Static Final intMax_offset =5;//5 pixel error, slide less than 5 pixels without animation    Private floatDownx;//Press the point when    Private floatViewxdown;//The location of the view when pressed    Private BooleanLastslidepull =false;//The direction of the last slide    Private floatMaxoffset =0;//max. Sliding distance    @Override    protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); System.out.println ("Debug:oncreate");        Setcontentview (R.layout.activity_main); Findviewbyid (r.id.btn_1). Setonclicklistener (NewOnclicklistener () {@Override             Public void OnClick(View arg0)            {slidetoshow ();        }        }); Findviewbyid (r.id.btn_2). Setonclicklistener (NewOnclicklistener () {@Override             Public void OnClick(View arg0)            {slidetohide ();        }        });        TvShow = (TextView) Findviewbyid (r.id.tv_show);    Initleftview (); }Private void Initleftview() {rl_left = (relativelayout) Findviewbyid (r.id.rl_left);        Rlwidth = Getresources (). Getdimensionpixelsize (R.dimen.rl_left_w); Rl_left.setx (-rlwidth);//Move the rl_left position to the left of the phone screen        //Initialize the Relativelayout view, here with the ListView exampleListView = (ListView) Rl_left.findviewbyid (R.id.lv_test); Listview.setadapter (NewArrayadapter<string> ( ThisAndroid.        R.layout.simple_expandable_list_item_1, GetItemData ()));    Listview.setonitemclicklistener (ItemListener); }/** * Fill false data * * @return  * *    PrivateList<string>GetItemData() {list<string> List =NewArraylist<string> (); for(inti =0; I < -; i++) {List.add ("Item"+ i); }returnList }PrivateOnitemclicklistener ItemListener =NewOnitemclicklistener () {@Override         Public void Onitemclick(adapterview<?> arg0, View arg1,intArg2,LongARG3) {slidetohide (); Tvshow.settext (String.Format ("You click Item%s!", arg2)); }    };/** * Use Valueanimator to bounce rl_left into the interface in animated form.    Private void Slidetoshow() {floatStartX = Rl_left.getx (); Valueanimator Valueanimator = Valueanimator.ofint ((int) StartX,0); Valueanimator.addupdatelistener (NewAnimatorupdatelistener () {@Override             Public void onanimationupdate(Valueanimator animation) {intoffset = (Integer) animation.getanimatedvalue ();            Rl_left.setx (offset);        }        }); Valueanimator.setinterpolator (NewDecelerateinterpolator ());floatfraction = Math.Abs (startx/rlwidth); Valueanimator.setduration ((Long) ( -* fraction));    Valueanimator.start (); }/** * Use Valueanimator to bounce rl_left out in animated form */    Private void Slidetohide() {floatStartX = Rl_left.getx (); Valueanimator Valueanimator = Valueanimator.ofint ((int) StartX,-rlwidth); Valueanimator.addupdatelistener (NewAnimatorupdatelistener () {@Override             Public void onanimationupdate(Valueanimator animation) {intoffset = (Integer) animation.getanimatedvalue ();            Rl_left.setx (offset);        }        }); Valueanimator.setinterpolator (NewDecelerateinterpolator ());floatfraction = Math.Abs ((rlwidth + StartX)/rlwidth); Valueanimator.setduration ((Long) ( -* fraction));    Valueanimator.start (); }@Override     Public Boolean ontouchevent(Motionevent event) {floatx = Event.getx ();Switch(Event.getaction ()) { CaseMotionevent.action_down: This. downx = x; This. Viewxdown = Rl_left.getx (); Break; CaseMotionevent.action_move:floatoffset = (Event.getx ()-DOWNX);//Sliding distance            floatPosX = Viewxdown + offset;//Calculate the possible locationsMaxoffset = maxoffset > Math.Abs (offset)? Maxoffset:math. ABS (offset);if(Offset >0) {// pull to showRl_left.setx (PosX <0? PosX:0);if(PosX >=0) {//Prevent against hand, update the value of Downx                     This. downx + = PosX; } Lastslidepull =true; }Else{//push to hideRl_left.setx (PosX >-rlwidth posX:-rlwidth);if(PosX <=-rlwidth) {//Prevent against hand, update the value of Downx                     This. Downx + = (PosX + rlwidth); } Lastslidepull =false; } Break; CaseMOTIONEVENT.ACTION_UP:if(Maxoffset < Max_offset) {//Prevent jitter                return Super. Ontouchevent (event); }//Use animation to slide to the specified position            if(Lastslidepull)            {slidetoshow (); }Else{slidetohide (); } Break;default: Break; }return Super. Ontouchevent (event); }@Override    protected void OnDestroy() {Super. OnDestroy (); }}
Effect

Forgive me, it's too troublesome to do a truncated gif.

More communication

Android Development Alliance QQ Group: 272209595

Android: Hand-sliding layout viewgroup

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.