重慶分公司,新征程啟航
為企業(yè)提供網(wǎng)站建設、域名注冊、服務器等服務
為企業(yè)提供網(wǎng)站建設、域名注冊、服務器等服務
這篇文章主要介紹Android如何根據(jù)手勢實現(xiàn)頂部View自動展示與隱藏效果,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供盧氏網(wǎng)站建設、盧氏做網(wǎng)站、盧氏網(wǎng)站設計、盧氏網(wǎng)站制作等企業(yè)網(wǎng)站建設、網(wǎng)頁設計與制作、盧氏企業(yè)網(wǎng)站模板建站服務,十年盧氏做網(wǎng)站經(jīng)驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡服務。
首先來看一下效果:
大體思路如下:
總體布局用了一個自定義的ViewGroup,里面包了兩個View(top View,bottomView)
我在bottomView里放了ViewPager,里面又有Fragment,F(xiàn)ragment里放的是ListView
原理:
ViewGroup在分發(fā)touchEvent的時候先通過手勢GestureDetector判斷手勢方向,當向上滑動的時候讓topView和bottomView同時向上移動,反之亦然。
整體思路不是很難如下是干貨:
布局文件
手勢監(jiān)聽重要的是打log看一下上下滑動是數(shù)值的變化,找到其規(guī)律:
@Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { Log.i(tag, "onScroll -> distanceY" + distanceY); if (distanceY < 0) {// 手勢向下滑動是負值 animatorLayoutOffset(1); } if (distanceY > 0) { animatorLayoutOffset(0f); } return true; }
一定記得在ViewGroup內(nèi)查找控件需要在onFinishInflate后才能找到:
@Override protected void onFinishInflate() { super.onFinishInflate(); viewTop = findViewById(R.id.group_top); viewBottom = findViewById(R.id.group_bottom); }
在ViewGroup布局的邏輯中需要處理的有一下幾點:
1、onMeasure的時候要把子控件測量出來
2、onLayout時需要手動將子控件布局
接下來就是監(jiān)聽手勢設置動畫,不停的onLayout以達到topView和bottomView的布局效果
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = MeasureSpec.getSize(widthMeasureSpec); int height = MeasureSpec.getSize(heightMeasureSpec); viewTop.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.AT_MOST)); viewBottom.measure(MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY)); setMeasuredDimension(width, height); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int topHeight = viewTop.getMeasuredHeight(); float offset = layoutOffset * topHeight; int width = r - l; float topViewYTop = offset - topHeight; float topViewYBottom = topViewYTop + topHeight; viewTop.layout(0, (int) topViewYTop, width, (int) topViewYBottom); viewBottom.layout(0, (int) topViewYBottom, width, (int) topViewYBottom + viewBottom.getMeasuredHeight()); } private void animatorLayoutOffset(float offset) { if (animator != null && animator.isRunning()) { return; } animator = ObjectAnimator.ofFloat(this, "layoutOffset", layoutOffset, offset); animator.setDuration(500); animator.start(); }
以上是“Android如何根據(jù)手勢實現(xiàn)頂部View自動展示與隱藏效果”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關知識,歡迎關注創(chuàng)新互聯(lián)行業(yè)資訊頻道!