Android簡單的浮窗
用過大眾點評和美團的都應該看到過這樣一個效果商品頁不斷向上滑動,購買的按鈕一直懸浮在那里
。我做了一個類似的效果,閑話不多說,先上圖了。
用Android Studio的同學教大家做gif的方法
- 首先保證全程手機與Android Studio連接
- 將項目運行在手機上,然后點擊下圖按鈕,點擊Start Recording開始錄制
錄制
- 接下來你就瘋狂操作你的手機,點擊Stop Recording保存視頻
- 然后就是將視頻轉化為gif,這一步需要用到PS。直接丟給UI,讓她幫你做吧,增進一下彼此的感情。
接下來開始講懸浮窗的實現過程。
- 首先需要自定義ScrollView,具體代碼如下。主要是自定義一個接口,將滾動時距離頂部的距離傳出去供外部調用。
public class MyScrollView extends ScrollView{ private OnScrollListener onScrollListener; public MyScrollView(Context context) { this(context, null); } public MyScrollView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MyScrollView(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle); } public void setOnScrollListener(OnScrollListener onScrollListener) { this.onScrollListener = onScrollListener; } @Override public int computeVerticalScrollRange() { return super.computeVerticalScrollRange(); } @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { super.onScrollChanged(l, t, oldl, oldt); if(onScrollListener != null){ onScrollListener.onScroll(t); } } public interface OnScrollListener{ public void onScroll(int scrollY); }}
- 然后是布局,如下圖。由于布局比較簡單,就不上代碼了。在頂部創建一個和中間創建一個同樣的懸浮窗。
布局
- 先講一下思路:1.開始時將兩個布局重合2.當中間的懸浮窗距離頂部的距離大于ScrollView滑動距離時,頂部懸浮窗的位置就是中間懸浮窗的位置,一直跟著中間懸浮窗3.當中間懸浮窗距離頂部的距離小于ScrollView滑動距離時,頂部懸浮窗的位置就是滑動的距離,一直懸浮在頂部。
public class SuspendActivity extends Activity implements MyScrollView.OnScrollListener{ / 自定義的MyScrollView / private MyScrollView myScrollView; / 在MyScrollView里面的購買布局 / private TextView mBuyLayout; /* 位于頂部的懸浮窗 */ private TextView mTopBuyLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_suspend); myScrollView = (MyScrollView) findViewById(R.id.scrollView); mBuyLayout = (TextView) findViewById(R.id.buy); mTopBuyLayout = (TextView) findViewById(R.id.top_buy_layout); myScrollView.setOnScrollListener(this); //當布局的狀態或者控件的可見性發生改變回調的接口 findViewById(R.id.parent_layout).getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { //這一步很重要,使得上面的購買布局和下面的購買布局重合 onScroll(myScrollView.getScrollY()); } }); } @Override public void onScroll(int scrollY) { int mBuyLayout2ParentTop = Math.max(scrollY, mBuyLayout.getTop()); mTopBuyLayout.layout(0, mBuyLayout2ParentTop, mTopBuyLayout.getWidth(), mBuyLayout2ParentTop + mTopBuyLayout.getHeight()); }}
參考: http://blog.csdn.net/xiaanming/article/details/17761431
文/劉小帥(簡書)
本文由用戶 AngusD45 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!