An example of sliding ListView to automatically hide the header and bottom elements of a page. listview to hide automatically

Source: Internet
Author: User
Tags gety

An example of sliding ListView to automatically hide the header and bottom elements of a page. listview to hide automatically

Complete engineering code here: https://github.com/NashLegend/Auto-Hide-ListView


Currently, many software products use this function to automatically hide the header and bottom elements of a page when sliding a list, such as Google +. When you first enter the Activity, the page is a list with a view at the bottom and a view at the header. When the list slides up, the header and tail elements are hidden to show more content, when the list slides down, pull out the header and tail elements. For example, Google +.


This is what it looks like:

 

Pull the list and hide its head and tail as follows:


If you pull it down, it will change back to the first image.


This function is implemented in this example.


In this example, the MainActivity layout is as follows. The ToolBar is the top element and the Button is the bottom element.

<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"    tools:context=".MainActivity">     <ListView        android:id="@+id/list_view"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:headerDividersEnabled="false" />     <android.support.v7.widget.Toolbar        android:id="@+id/action_bar"        android:layout_width="match_parent"        android:layout_height="?attr/actionBarSize"        android:background="@android:color/holo_blue_light" />     <Button        android:id="@+id/footer"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentBottom="true"        android:text="@string/ScrollDown" /></RelativeLayout>

Public class MainActivity extends ActionBarActivity {ListView listView; Toolbar toolbar; View header; View footer; int touchSlop = 10; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); touchSlop = (int) (ViewConfiguration. get (MainActivity. this ). getScaledTouchSlop () * 0.9); // calculates whether to hide/show the header and tail elements after the distance between them is exceeded. The default touchslop is used 0.9 times. ListView = (ListView) findViewById (R. id. list_view); footer = findViewById (R. id. footer); toolbar = (Toolbar) findViewById (R. id. action_bar); // The following sentence sets this ToolBar as ActionBar. In this example, this sentence is not needed, but if this sentence is used, you have to set Theme to NoActionBar. It has nothing to say here. For details, see Style setSupportActionBar (toolbar) in the link above; // fill in the element for this ListView. String [] str = new String [64]; for (int I = 0; I <str. length; I ++) {str [I] = "Android" + I ;}// R. layout. simple_layout is a TextView. For details, see the above link ...... ArrayAdapter <String> adapter = new ArrayAdapter <> (MainActivity. this, R. layout. simple_layout, str); listView. setAdapter (adapter); // Add a Header for the ListView, which is as high as the ToolBar. In this way, we can correctly see the first element in the list without being overwritten. Header = new View (MainActivity. this); header. setLayoutParams (new AbsListView. layoutParams (ViewGroup. layoutParams. MATCH_PARENT, (int) getResources (). getDimension (R. dimen. abc_action_bar_default_height_material); header. setBackgroundColor (Color. parseColor ("#00000000"); listView. addHeaderView (header); // set the touch event and scroll event for ListView, which is the core listView. setOnTouchListener (onTouchListener); listView. setOnScrollList Ener (onScrollListener); footer. setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {// set a click event for the button and click to scroll 10 items listView at a time. smoothScrollByOffset (10) ;}}) ;}@ Override public boolean onCreateOptionsMenu (Menu menu) {getMenuInflater (). inflate (R. menu. menu_main, menu); return true;} @ Override public boolean onOptionsItemSelected (MenuItem item) {int id = item. getIte MId (); if (id = R. id. action_settings) {return true;} return super. onOptionsItemSelected (item);} AnimatorSet backAnimatorSet; // This is the animation private void animateBack () used to display the header and tail elements {// clear other animations first if (hideAnimatorSet! = Null & hideAnimatorSet. isRunning () {hideAnimatorSet. cancel () ;}if (backAnimatorSet! = Null & backAnimatorSet. isRunning () {// If the animation is already running, ignore it} else {backAnimatorSet = new AnimatorSet (); // The following two sentences are used to place the header and tail elements back in the initial position. ObjectAnimator headerAnimator = ObjectAnimator. ofFloat (toolbar, "translationY", toolbar. getTranslationY (), 0f); ObjectAnimator footerAnimator = ObjectAnimator. ofFloat (footer, "translationY", footer. getTranslationY (), 0f); ArrayList <Animator> animators = new ArrayList <> (); animators. add (headerAnimator); animators. add (footerAnimator); backAnimatorSet. setDuration (300); backAnimatorSet. playTogether (Imators); backAnimatorSet. start () ;}} AnimatorSet hideAnimatorSet; // This is the animation private void animateHide () used to hide the header and tail elements {// clear other animations first if (backAnimatorSet! = Null & backAnimatorSet. isRunning () {backAnimatorSet. cancel ();} if (hideAnimatorSet! = Null & hideAnimatorSet. isRunning () {// If the animation is already running, it does not matter} else {hideAnimatorSet = new AnimatorSet (); ObjectAnimator headerAnimator = ObjectAnimator. ofFloat (toolbar, "translationY", toolbar. getTranslationY (),-toolbar. getHeight (); // hide the ToolBar to ObjectAnimator footerAnimator = ObjectAnimator. ofFloat (footer, "translationY", footer. getTranslationY (), footer. getHeight (); // hide the Button to the ArrayList below <Animator> animators = new ArrayList <> (); animators. add (headerAnimator); animators. add (footerAnimator); hideAnimatorSet. setDuration (200); hideAnimatorSet. playTogether (animators); hideAnimatorSet. start () ;}} View. onTouchListener onTouchListener = new View. onTouchListener () {float lastY = 0f; float currentY = 0f; // The following two indicate the sliding direction. If the value is greater than 0, the sliding is downward. If the value is smaller than 0, the sliding is upward, equal to 0 indicates that int lastDirection = 0 is not sliding; int currentDirectio N = 0; @ Override public boolean onTouch (View v, MotionEvent event) {switch (event. getAction () {case MotionEvent. ACTION_DOWN: lastY = event. getY (); currentY = event. getY (); currentDirection = 0; lastDirection = 0; break; case MotionEvent. ACTION_MOVE: if (listView. getFirstVisiblePosition ()> 0) {// only available in listView. when getFirstVisiblePosition ()> 0, you can determine whether to enable explicit/hidden animation. Because listView. when getFirstVisiblePosition () = 0, // ToolBar -- that is, the Header element must be visible. If it is hidden at this time, if headerview is used for placeholder placement, it will be discovered by the user. // However, when the user displays the headerview of the list from the drop-down list, the header and tail elements must appear again before they can be determined. This judgment is written in the onScrollListener ...... Float tmpCurrentY = event. getY (); if (Math. abs (tmpCurrentY-lastY)> touchSlop) {// determine currentY = tmpCurrentY when the sliding distance is greater than touchslop; currentDirection = (int) (currentY-lastY); if (lastDirection! = CurrentDirection) {// if it is different from the previous direction, execute the explicit/hidden animation if (currentDirection <0) {animateHide () ;}else {animateBack ();}}}} break; case MotionEvent. ACTION_CANCEL: case MotionEvent. ACTION_UP: // set currentDirection to 0 when the finger is lifted, so that no matter where you pull it next time, all are different from the current one (in fact, this is not needed after being written in ACTION_DOWN ......) CurrentDirection = 0; lastDirection = 0; break;} return false ;}}; AbsListView. onScrollListener onScrollListener = new AbsListView. onScrollListener () {// This Listener is used to deal with the situation where the list is still sliding after the user's hand leaves the list, that is, SCROLL_STATE_FLING int lastPosition = 0; // The Position of the first visible element that was last rolled to in the listview -- firstVisibleItem int state = SCROLL_STATE_IDLE; @ Override public void onScrollStateChanged (AbsListView view, int scrollState) {// record when Previous list status state = scrollState;} @ Override public void onScroll (AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {if (firstVisibleItem = 0) {animateBack ();} if (firstVisibleItem> 0) {if (firstVisibleItem> lastPosition & state = SCROLL_STATE_FLING) {// if the last position is smaller than the current position, hide the first and last element animateHide ();} // ====================================== if (firstVisibleItem <lastPosition & State = SCROLL_STATE_FLING) {// if the last position is greater than the current position, the header and tail elements are displayed. In this example, this if is useless. // if it is triggered by sliding ListView, then, animateBack () must have been executed, so there is no need to // if you click the button to trigger the scroll, then according to the design principle, the button must be one of the first and last elements, therefore, animateBack () // is not required for the if block. Therefore, this if block is not required. The value is "animateBack ();} // not determined here (firstVisibleItem = lastPosition & state = SCROLL_STATE_FLING) however, if a single item in the list is long, you still need to judge it, but the Code requires several more lines, when sliding is triggered, drag and execute animateHide () or animateBack (). In this example, the click event is written in.) // BTW. if the slide of the list is just a slide list by hand, rather than clicking a button to roll to a certain position, the first if is enough...} LastPosition = firstVisibleItem ;}};}


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.