search
HomeWeb Front-endHTML TutorialExample of sliding ListView to automatically hide the head and bottom elements of the page_html/css_WEB-ITnose

The complete engineering code is here: https://github.com/NashLegend/Auto-Hide-ListView


Many software now have this kind of sliding The function of automatically hiding the head and bottom elements of the page when listing, 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 head. When the list slides up, the head and tail elements are hidden to show more content. When the list slides down, the Pull out the head and tail elements. Such as Google.


This is what it looked like when you first entered:

Pull the list over again, hiding the head and tail, and it’s done It looks like this:


If you scroll down, it will change back to the first picture.


This example implements this function


In this example, the layout of MainActivity is as follows, and ToolBar is the top element , 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"></listview>     <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"></android.support.v7.widget.toolbar>     <button android:id="@+id/footer" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignparentbottom="true" android:text="@string/ScrollDown"></button></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);//滚动过多少距离后才开始计算是否隐藏/显示头尾元素。这里用了默认touchslop的0.9倍。        listView = (ListView) findViewById(R.id.list_view);        footer = findViewById(R.id.footer);        toolbar = (Toolbar) findViewById(R.id.action_bar);        // 下面这句将这个ToolBar设置为ActionBar,在这个例子里面,这句其实用不着,但是如果用了这句,就得把Theme设置为NoActionBar了,无关这里要说的,具体见上面的链接中的Style        setSupportActionBar(toolbar);                 //为这个ListView填充元素。        String[] str = new String[64];        for (int i = 0; i  adapter = new ArrayAdapter(MainActivity.this, R.layout.simple_layout, str);        listView.setAdapter(adapter);                 //为ListView添加一个Header,这个Header与ToolBar一样高。这样我们可以正确的看到列表中的第一个元素而不被遮住。        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);                 //为ListView设置触摸事件和滚动事件,这是核心        listView.setOnTouchListener(onTouchListener);        listView.setOnScrollListener(onScrollListener);        footer.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                //为button设置点击事件,点击一次滚动10个item                listView.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.getItemId();        if (id == R.id.action_settings) {            return true;        }        return super.onOptionsItemSelected(item);    }     AnimatorSet backAnimatorSet;//这是显示头尾元素使用的动画     private void animateBack() {        //先清除其他动画        if (hideAnimatorSet != null && hideAnimatorSet.isRunning()) {            hideAnimatorSet.cancel();        }        if (backAnimatorSet != null && backAnimatorSet.isRunning()) {            //如果这个动画已经在运行了,就不管它        } else {            backAnimatorSet = new AnimatorSet();            //下面两句是将头尾元素放回初始位置。            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(animators);            backAnimatorSet.start();        }    }     AnimatorSet hideAnimatorSet;//这是隐藏头尾元素使用的动画     private void animateHide() {        //先清除其他动画        if (backAnimatorSet != null && backAnimatorSet.isRunning()) {            backAnimatorSet.cancel();        }        if (hideAnimatorSet != null && hideAnimatorSet.isRunning()) {            //如果这个动画已经在运行了,就不管它        } else {            hideAnimatorSet = new AnimatorSet();            ObjectAnimator headerAnimator = ObjectAnimator.ofFloat(toolbar, "translationY", toolbar.getTranslationY(), -toolbar.getHeight());//将ToolBar隐藏到上面            ObjectAnimator footerAnimator = ObjectAnimator.ofFloat(footer, "translationY", footer.getTranslationY(), footer.getHeight());//将Button隐藏到下面            ArrayList<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;        //下面两个表示滑动的方向,大于0表示向下滑动,小于0表示向上滑动,等于0表示未滑动        int lastDirection = 0;        int currentDirection = 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) {                        //只有在listView.getFirstVisiblePosition()>0的时候才判断是否进行显隐动画。因为listView.getFirstVisiblePosition()==0时,                        //ToolBar??也就是头部元素必须是可见的,如果这时候隐藏了起来,那么占位置用了headerview就被用户发现了                        //但是当用户将列表向下拉露出列表的headerview的时候,应该要让头尾元素再次出现才对??这个判断写在了后面onScrollListener里面……                        float tmpCurrentY = event.getY();                        if (Math.abs(tmpCurrentY - lastY) > touchSlop) {//滑动距离大于touchslop时才进行判断                            currentY = tmpCurrentY;                            currentDirection = (int) (currentY - lastY);                            if (lastDirection != currentDirection) {                                //如果与上次方向不同,则执行显/隐动画                                if (currentDirection  0) {                if (firstVisibleItem > lastPosition && state == SCROLL_STATE_FLING) {                    //如果上次的位置小于当前位置,那么隐藏头尾元素                    animateHide();                }                                 //================================                if (firstVisibleItem  <br> <br> <p></p> </animator></animator>
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

HTML in Action: Examples of Website StructureHTML in Action: Examples of Website StructureMay 05, 2025 am 12:03 AM

HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

How do you insert an image into an HTML page?How do you insert an image into an HTML page?May 04, 2025 am 12:02 AM

ToinsertanimageintoanHTMLpage,usethetagwithsrcandaltattributes.1)UsealttextforaccessibilityandSEO.2)Implementsrcsetforresponsiveimages.3)Applylazyloadingwithloading="lazy"tooptimizeperformance.4)OptimizeimagesusingtoolslikeImageOptimtoreduc

HTML's Purpose: Enabling Web Browsers to Display ContentHTML's Purpose: Enabling Web Browsers to Display ContentMay 03, 2025 am 12:03 AM

The core purpose of HTML is to enable the browser to understand and display web content. 1. HTML defines the web page structure and content through tags, such as, to, etc. 2. HTML5 enhances multimedia support and introduces and tags. 3.HTML provides form elements to support user interaction. 4. Optimizing HTML code can improve web page performance, such as reducing HTTP requests and compressing HTML.

Why are HTML tags important for web development?Why are HTML tags important for web development?May 02, 2025 am 12:03 AM

HTMLtagsareessentialforwebdevelopmentastheystructureandenhancewebpages.1)Theydefinelayout,semantics,andinteractivity.2)SemantictagsimproveaccessibilityandSEO.3)Properuseoftagscanoptimizeperformanceandensurecross-browsercompatibility.

Explain the importance of using consistent coding style for HTML tags and attributes.Explain the importance of using consistent coding style for HTML tags and attributes.May 01, 2025 am 12:01 AM

A consistent HTML encoding style is important because it improves the readability, maintainability and efficiency of the code. 1) Use lowercase tags and attributes, 2) Keep consistent indentation, 3) Select and stick to single or double quotes, 4) Avoid mixing different styles in projects, 5) Use automation tools such as Prettier or ESLint to ensure consistency in styles.

How to implement multi-project carousel in Bootstrap 4?How to implement multi-project carousel in Bootstrap 4?Apr 30, 2025 pm 03:24 PM

Solution to implement multi-project carousel in Bootstrap4 Implementing multi-project carousel in Bootstrap4 is not an easy task. Although Bootstrap...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.