Android自訂ScrollView實現一鍵置頂功能

來源:互聯網
上載者:User

標籤:

如下:

(ps:動態圖有太大了,上傳不了,就給大家口述一下要實現的功能吧)

要實現的功能:當ScrollView向上滑動超過一定距離後,就漸層的出現一個置頂的按鈕,當滑動距離小於我們指定的距離時,按鈕又消失。

實現原理:就是監聽View的onScrollChanged()方法(回調方法),擷取到ScrolView滑動的距離,如果大於我們的距離,則出現置頂按鈕,否則,直接隱藏,且當按鈕出現點擊事件,讓整個ScrollView滑動到(0,0)位置即可,不廢話,直接上代碼

 

自訂的ScrollView類:GoTopScrollView.java

package com.tianti.meilishuo.customcontrol;import android.content.Context;import android.util.AttributeSet;import android.view.View;import android.view.View.OnClickListener;import android.widget.ImageView;import android.widget.ScrollView;import com.tianti.meilishuo.R;public class GoTopScrollView extends ScrollView implements OnClickListener{private ImageView goTopBtn;private int screenHeight;public GoTopScrollView(Context context, AttributeSet attrs){super(context, attrs);}public void setScrollListener(ImageView goTopBtn){this.goTopBtn = goTopBtn;this.goTopBtn.setOnClickListener(this);}@Overrideprotected void onScrollChanged(int l, int t, int oldl, int oldt){super.onScrollChanged(l, t, oldl, oldt);/** * 滑動距離超過500px,出現向上按鈕,可以做為自訂屬性 */if (t >= 500){goTopBtn.setVisibility(View.VISIBLE);}else{goTopBtn.setVisibility(View.GONE);}}@Overridepublic void onClick(View v){if (v.getId() == R.id.iv_fragmenthome_goTop){this.smoothScrollTo(0, 0);}}}

  

只需要在主函數中調用一下


goTopScrollview.setScrollListener(iv_fragmenthome_goTop); //裡面的參數就是那張小圖片

 

 

Android自訂ScrollView實現一鍵置頂功能

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.