Android ListView, ScrollView back to top button

Source: Internet
Author: User


On top of some of the ListView and ScrollView, when sliding to the bottom, there will be a button back at the bottom of the lower right corner to provide a better user experience.

As follows:



Layout

First say the layout, you can use the frame layout framelayout, you can also use the relative layout relativelayout. Look at the layout file for the ListView:

<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:backg Round= "@android: Color/white" > <listview android:id= "@+id/my_listview" android:layout_width= "fill_p Arent "android:layout_height=" wrap_content "android:layout_marginleft=" 10DP "Android:layout_marginrig ht= "10DP"/> <button android:id= "@+id/top_btn" android:layout_width= "50DP" android:layout_he ight= "50DP" android:visibility= "Gone" android:layout_alignparentbottom= "true" Android:layout_alignpar Entright= "true" android:layout_marginbottom= "6DP" android:layout_marginright= "6DP" Android:background = "@drawable/top_btn_bg" android:gravity= "center" android:text= "Top"/></relativelayout>


Listview back to the top of the activity code is the code found on the Internet, the author is: Zihao
/** * Main interface * * @author Zihao * @details Because some phones have virtual keys (in the calculation of screen resolution, some can be removed from the virtual area of the region, such as Samsung, some do not-like MX3), in order to calculate the accuracy, * You can set activity to theme *. Notitlebar.fullscreen fills the screen (solving a similar MX3 that calculates the virtual keyboard into the screen height during the calculation). */public class Listactivity extends Activity implements Onclicklistener {private ListView listview;//list data listing private but ton totopbtn;//return top button Private Myadapter adapter;private boolean scrollflag = false;//mark whether to slide private int lastvisibleitemp Osition = 0;//marks the last sliding position @overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate ); Setcontentview (r.layout.activity_list); Initview ();} /** * Initialize view */private void Initview () {listview = (ListView) Findviewbyid (R.id.my_listview); totopbtn = (Button) Findviewby Id (r.id.top_btn); adapter = new Myadapter (this, Gettitledatas ()); Listview.setadapter (adapter); Totopbtn.setonclicklistener (this); Listview.setonscrolllistener (new Onscrolllistener () {@Overridepublic void Onscrollstatechanged (abslistview view, int scrollstATE) {//TODO auto-generated method Stubswitch (scrollstate) {//When not scrolling case onscrolllistener.scroll_state_idle:// is when the screen stops scrolling Scrollflag = false;//determines the scroll to the bottom if (listview.getlastvisibleposition () = = (Listview.getcount ()-1)) { Totopbtn.setvisibility (view.visible);} Judge Scroll to Top if (listview.getfirstvisibleposition () = = 0) {totopbtn.setvisibility (view.gone);} Break;case onscrolllistener.scroll_state_touch_scroll://when scrolling scrollflag = True;break;case OnScrollListener.SCROLL_ STATE_FLING://is when the user is driven by the screen and raised his finger, the screen produces inertia sliding scrollflag = False;break;}} /** * Firstvisibleitem: The first list item ID currently visible (starting from 0) * VisibleItemCount: Number of list items currently visible (small half is counted) Totalitemcount: list items Total */@ overridepublic void Onscroll (abslistview view, int firstvisibleitem,int visibleitemcount, int totalitemcount) {// Show or hide the top button if (scrollflag&& screenutil.getscreenviewbottomheight (ListView) When you start sliding and the y-axis point at the bottom of the ListView exceeds the maximum range of the screen >= screenutil.getscreenheight (listactivity.this)) {if (Firstvisibleitem > Lastvisibleitemposition) {// Top Slide totopbtn.setvisibility (View. VISIBLE);} else if (Firstvisibleitem < lastvisibleitemposition) {//Slide totopbtn.setvisibility (view.gone);} else {return;} Lastvisibleitemposition = Firstvisibleitem;}});} /** * Get Header Data list * * @return */private list<string> gettitledatas () {list<string> Titlearray = new Arraylist&lt ; String> (); for (int i = 0; i <; i++) {Titlearray.add ("This is the first" + i + "item");} return Titlearray;} /** * Scroll the listview to the specified position * * @param pos */private void setlistviewpos (int pos) {if (Android.os.Build.VERSION.SDK_INT >= 8 ) {listview.smoothscrolltoposition (pos);} else {listview.setselection (pos);}} @Overridepublic void OnClick (View v) {//TODO auto-generated method Stubswitch (V.getid ()) {Case r.id.top_btn://click button to return to Li Stview's first setlistviewpos (0);

In the above code, the ListView is set Setonscrolllistener Listen, when a bit of sliding (can also provide a value) or at the bottom of the time will appear back to the top button.

ScrollView's Code

There are a lot of knowledge points:

    1. scrollview slide to stop monitoring.
    2. scrollview back to the top, or to the bottom of the method.
    3. scrollview to reach the top or bottom of the judgment method.

The reference connections above are also written in the comments.

public class Scrollviewactivity extends Activity implements Onclicklistener {private ScrollView scrollview;//  ScrollView Data List Private button totopbtn;//return top button private int scrolly = 0;//mark last sliding position private View contentview;private final String tag= "test"; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_scroll); Initview ();}  /** * Initialize view */private void Initview () {ScrollView = (ScrollView) Findviewbyid (R.id.my_scrollview); if (Contentview = = null) {Contentview = scrollview.getchildat (0);} TOTOPBTN = (Button) Findviewbyid (R.ID.TOP_BTN); Totopbtn.setonclicklistener (this);//http://blog.csdn.net/ jiangwei0910410003/article/details/17024287/******************** monitor ScrollView Slide Stop *****************************/ Scrollview.setontouchlistener (New Ontouchlistener () {private int lasty = 0;private int toucheventid =-9983761; Handler Handler = new Handler () {@Overridepublic void Handlemessage (Message msg) {super.handlemessage (msg); VieW scroller = (View) msg.obj;if (msg.what = = Toucheventid) {if (lasty = = scroller.getscrolly ()) {handlestop (scroller);} els e {handler.sendmessagedelayed (Handler.obtainmessage (Toucheventid, Scroller), 5); lasty = Scroller.getscrolly ();}}}; public boolean OnTouch (View V, motionevent event) {if (event.getaction () = = motionevent.action_up) { Handler.sendmessagedelayed (Handler.obtainmessage (Toucheventid, v), 5);} return false;} /** * ScrollView Stop * * @param view */private void Handlestop (Object view) {log.i (TAG, "handlestop"); ScrollView scroller = (ScrollView) view;scrolly = scroller.getscrolly ();d oonborderlistener ();}); /}/** * ScrollView top, bottom judgment: * http://www.trinea.cn/ android/on-bottom-load-more-scrollview-impl/* * Where getchildat means to get ScrollView's child view, because ScrollView only allows a child * view , so Contentview.getmeasuredheight () indicates the height of the child view, * getscrolly () indicates the scroll distance of the y-axis, getheight () is the height of the ScrollView. * When the getscrolly () reaches the maximum and the height of the scrollview is equal to the high of its contentAh ~ * * @param pos */private void Doonborderlistener () {log.i (Tag,screenutil.getscreenviewbottomheight (ScrollView) + ") "+ scrollview.getscrolly () +" "+ screenutil.getscreenheight (scrollviewactivity.this));//Bottom judgment if (contentview! = null && contentview.getmeasuredheight () <= scrollview.getscrolly () + scrollview.getheight ()) { Totopbtn.setvisibility (view.visible); LOG.I (TAG, "Bottom");} The top determines else if (scrollview.getscrolly () = = 0) {log.i (TAG, "top");} else if (scrollview.getscrolly () >) {totopbtn.setvisibility (view.visible); LOG.I (TAG, "Test");}} /** * Below we look at this function: Scrollview.fullscroll (scrollview.focus_down); scroll to the bottom * Scrollview.fullscroll (SCROLLVIEW.FOCUS_UP); Scroll to the top * * * Note that the method cannot be called directly because many of the Android functions are based on Message Queuing to synchronize, so need an action, * after AddView, not equal to immediately appear, but in the queue waiting for processing, although soon, However, if Fullscroll is called immediately, * view may not yet be displayed, so failure should be updated by handler in the new thread * http://blog.csdn.net/t12x3456/article/details/ 12799825 * HTTP://WWW.TUICOOL.COM/ARTICLES/ZAYIJQ */@Overridepublic void OnClick (View v) {//TODO Auto-geneRated Method Stubswitch (V.getid ()) {case R.id.top_btn:scrollview.post (new Runnable () {@Overridepublic void run () {Scrol Lview.fullscroll (SCROLLVIEW.FOCUS_UP);}}); Totopbtn.setvisibility (view.gone); break;}}}

Many details are commented in the code, and the reference link has been added. Everyone download the code to perform a look.

Code http://download.csdn.net/detail/jjdhshdahhdd/9059757

Copyright NOTICE: This article is for Bo Master original article, welcome reprint, please indicate source.

Android ListView, ScrollView back to top button

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.