Android自定義ViewGroup(側(cè)滑菜單)詳解及簡單實例
自定義側(cè)滑菜單的簡單實現(xiàn)
不少APP中都有這種側(cè)滑菜單,例如QQ這類的,比較有名開源庫如slidingmenu。
有興趣的可以去研究研究這個開源庫。
這里我們將一種自己的實現(xiàn)方法,把學(xué)習(xí)的 東西做個記錄,O(∩_∩)O!
首先看效果圖:

這里我們實現(xiàn)的側(cè)滑菜單,是將左側(cè)隱藏的菜單和主面板看作一個整體來實現(xiàn)的,而左側(cè)隱藏的菜單和主面板相當(dāng)于是這個自定義View的子View。
首先來構(gòu)造該自定義View的布局:
自定義的SlideMenuView包含兩個子view,一個是menuView,另一個是mainView(主面板)。
<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="${relativePackage}.${activityClass}" >
<com.wind.view.SlideMenuView
android:id="@+id/slideMenu"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<include layout="@layout/layout_menu"/>
<include layout="@layout/layout_main"/>
</com.wind.view.SlideMenuView>
</RelativeLayout>
接著我們需要實現(xiàn)SlideMenuView的 java代碼。
自定義VIew,需要繼承某個父類,通過重寫父類的某些方法來增強父類的功能。
這里我們選擇繼承ViewGroup,一般自定義View,需要重寫onMeasure,onLayout和onDraw,正常情況下只要重寫onDraw就可以了,特殊情況下,需要重寫onMeasure 和onLayout。
package com.wind.view;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Scroller;
public class SlideMenuView extends ViewGroup { // FrameLayout {
private static final String TAG = "SlideMenuView";
private View menuView, mainView;
private int menuWidth = 0;
private Scroller scroller;
public SlideMenuView(Context context) {
super(context);
init();
}
public SlideMenuView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
scroller = new Scroller(getContext());
}
/**
* 當(dāng)一級的子View全部加載玩后調(diào)用,可以用于初始化子View的引用
*
*/
@Override
protected void onFinishInflate() {
super.onFinishInflate();
menuView = getChildAt(0);
mainView = getChildAt(1);
menuWidth = menuView.getLayoutParams().width;
Log.d(TAG, "onFinishInflate() menuWidth: " + menuWidth);
}
/**
* widthMeasureSpec和heightMeasureSpec是系統(tǒng)測量SlideMenu時傳入的參數(shù),
* 這2個參數(shù)測量出的寬高能讓SlideMenu充滿窗體,其實是正好等于屏幕寬高
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Log.d(TAG, "onMeasure: widthMeasureSpec: " + widthMeasureSpec
+ "heightMeasureSpec: " + heightMeasureSpec);
// int measureSpec = MeasureSpec.makeMeasureSpec(menuWidth,
// MeasureSpec.EXACTLY);
//
// Log.d(TAG,"onMeasure: measureSpec: " +measureSpec);
// 測量所有子view的寬高
// 通過getLayoutParams方法可以獲取到布局文件中指定寬高
menuView.measure(widthMeasureSpec, heightMeasureSpec);
// 直接使用SlideMenu的測量參數(shù),因為它的寬高都是充滿父窗體
mainView.measure(widthMeasureSpec, heightMeasureSpec);
}
/**
* 重新擺放子View的位置
* l: 當(dāng)前子view的左邊在父view的坐標(biāo)系中的x坐標(biāo)
* t: 當(dāng)前子view的頂邊在父view的坐標(biāo)系中的y坐標(biāo)
*/
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
Log.d(TAG, "onLayout() changed: " + changed + "l: " + l + "t: " + t
+ "r: " + r + "b: " + b);
Log.d(TAG,"menuView.getMeasuredHeight(): " + menuView.getMeasuredHeight());
menuView.layout(-menuWidth, 0, 0, menuView.getMeasuredHeight());
mainView.layout(0, 0, r, b);
}
private int downX;
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
downX = (int) event.getX();
break;
case MotionEvent.ACTION_MOVE:
int moveX = (int) event.getX();
int deltaX = (moveX - downX);
Log.e(TAG, "scrollX: " + getScrollX());
int newScrollX = getScrollX() - deltaX;
//使得SlideMenuView不會滑動出界
if(newScrollX > 0) newScrollX = 0;
if(newScrollX < -menuWidth) newScrollX = -menuWidth;
scrollTo(newScrollX, 0);
Log.e(TAG, "moveX: " + moveX);
downX = moveX;
break;
case MotionEvent.ACTION_UP:
//①.使用自定義動畫
// ScrollAnimation scrollAnimation;
// if(getScrollX()>-menuWidth/2){
// //關(guān)閉菜單
//// scrollTo(0, 0);
// scrollAnimation = new ScrollAnimation(this, 0);
// }else {
// //打開菜單
//// scrollTo(-menuWidth, 0);
// scrollAnimation = new ScrollAnimation(this, -menuWidth);
// }
// startAnimation(scrollAnimation);
//②使用Scroller
if(getScrollX()>-menuWidth/2){
// //關(guān)閉菜單
closeMenu();
}else {
//打開菜單
openMenu();
}
break;
}
return true;
}
private void openMenu() {
Log.d(TAG, "openMenu...");
scroller.startScroll(getScrollX(), 0, -menuWidth-getScrollX(), 400);
invalidate();
}
private void closeMenu() {
Log.d(TAG, "closeMenu...");
scroller.startScroll(getScrollX(), 0, 0-getScrollX(), 400);
invalidate();
}
/**
* Scroller不主動去調(diào)用這個方法
* 而invalidate()可以掉這個方法
* invalidate->draw->computeScroll
*/
@Override
public void computeScroll() {
super.computeScroll();
if(scroller.computeScrollOffset()){//返回true,表示動畫沒結(jié)束
scrollTo(scroller.getCurrX(), 0);
invalidate();
}
}
//用于在Activity中來控制菜單的狀態(tài)
public void switchMenu() {
if(getScrollX() == 0) {
openMenu();
} else {
closeMenu();
}
}
}
- 這里繼承ViewGroup,由于子View都是利用系統(tǒng)的控件填充,所以不需要重寫onDraw方法。
- 由于是繼承自ViewGroup,需要實現(xiàn)onMeasure來測量兩個子View的高度和寬度。我們還可以繼承FrameLayout,則不需要實現(xiàn)onMeasure,因為FrameLayout已經(jīng)幫我們實現(xiàn)onMeasure。
- 重寫onLayout方法,重新定義自定義的位置擺放,左側(cè)的側(cè)滑菜單需要使其處于隱藏狀態(tài)。
- 重寫onTouch方法,通過監(jiān)測Touch的Up和Down來滑動View來實現(xiàn)側(cè)滑的效果。
關(guān)于平滑滾動
我們可以采用Scroller類中的startScroll來實現(xiàn)平滑滾動,同樣我們可以使用自定義動畫的方式來實現(xiàn)。
package com.wind.view;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;
/**
* 讓指定view在一段時間內(nèi)scrollTo到指定位置
* @author Administrator
*
*/
public class ScrollAnimation extends Animation{
private View view;
private int targetScrollX;
private int startScrollX;
private int totalValue;
public ScrollAnimation(View view, int targetScrollX) {
super();
this.view = view;
this.targetScrollX = targetScrollX;
startScrollX = view.getScrollX();
totalValue = this.targetScrollX - startScrollX;
int time = Math.abs(totalValue);
setDuration(time);
}
/**
* 在指定的時間內(nèi)一直執(zhí)行該方法,直到動畫結(jié)束
* interpolatedTime:0-1 標(biāo)識動畫執(zhí)行的進度或者百分比
* time : 0 - 0.5 - 0.7 - 1
* value: 10 - 60 - 80 - 110
* 當(dāng)前的值 = 起始值 + 總的差值*interpolatedTime
*/
@Override
protected void applyTransformation(float interpolatedTime,
Transformation t) {
super.applyTransformation(interpolatedTime, t);
int currentScrollX = (int) (startScrollX + totalValue*interpolatedTime);
view.scrollTo(currentScrollX, 0);
}
}
如上面的代碼:
通過自定義動畫來讓View在一段時間內(nèi)重復(fù)執(zhí)行這個動作。
關(guān)于getScrollX
將View向右移動的時候,通過View.getScrollX得到的值是負(fù)的。
其實可以這樣理解:
*getScrollX()表示的是當(dāng)前的屏幕x坐標(biāo)的最小值-移動的距離(向右滑動時移動的距離為正值,
向左滑動時移動的距離為負(fù)值)。*
對scrollTo和scrollBy的理解
我們查看View的源碼發(fā)現(xiàn),scrollBy其實調(diào)用的就是scrollTo,scrollTo就是把View移動到屏幕的X和Y位置,也就是絕對位置。而scrollBy其實就是調(diào)用的scrollTo,但是參數(shù)是當(dāng)前mScrollX和mScrollY加上X和Y的位置,所以ScrollBy調(diào)用的是相對于mScrollX和mScrollY的位置。
我們在上面的代碼中可以看到當(dāng)我們手指不放移動屏幕時,就會調(diào)用scrollBy來移動一段相對的距離。而當(dāng)我們手指松開后,會調(diào)用mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);來產(chǎn)生一段動畫來移動到相應(yīng)的頁面,在這個過程中系統(tǒng)回不斷調(diào)用computeScroll(),我們再使用scrollTo來把View移動到當(dāng)前Scroller所在的絕對位置。
/**
* Set the scrolled position of your view. This will cause a call to
* {@link #onScrollChanged(int, int, int, int)} and the view will be
* invalidated.
* @param x the x position to scroll to
* @param y the y position to scroll to
*/
public void scrollTo(int x, int y) {
if (mScrollX != x || mScrollY != y) {
int oldX = mScrollX;
int oldY = mScrollY;
mScrollX = x;
mScrollY = y;
invalidateParentCaches();
onScrollChanged(mScrollX, mScrollY, oldX, oldY);
if (!awakenScrollBars()) {
invalidate(true);
}
}
}
/**
* Move the scrolled position of your view. This will cause a call to
* {@link #onScrollChanged(int, int, int, int)} and the view will be
* invalidated.
* @param x the amount of pixels to scroll by horizontally
* @param y the amount of pixels to scroll by vertically
*/
public void scrollBy(int x, int y) {
scrollTo(mScrollX + x, mScrollY + y);
}
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
Android ViewPager自定義輪播圖并解決播放沖突
這篇文章主要為大家詳細(xì)介紹了Android ViewPager自定義輪播圖并解決播放沖突,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09
Android-如何將RGB彩色圖轉(zhuǎn)換為灰度圖方法介紹
本文將詳細(xì)介紹Android-如何將RGB彩色圖轉(zhuǎn)換為灰度圖方法,需要了解更多的朋友可以參考下2012-11-11
android 開發(fā) 文件讀寫應(yīng)用案例分析
在Android應(yīng)用中保存文件會使用到文件讀寫技術(shù),本文將詳細(xì)介紹,需要的朋友可以參考下2012-12-12
詳解如何在Android中實現(xiàn)懸浮Activity
本篇文章主要介紹詳解如何在Android中實現(xiàn)懸浮Activity,通過修改Activity的實現(xiàn)來適配平板設(shè)備,已達(dá)到代碼的最大利用率。有興趣的可以了解一下。2017-01-01
Android自定義view利用Xfermode實現(xiàn)動態(tài)文字加載動畫
這篇文章主要介紹了Android自定義view利用Xfermode實現(xiàn)動態(tài)文字加載動畫,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07
Android模擬器"Failed To Allocate memory 8"錯誤如何解決
這篇文章主要介紹了Android模擬器"Failed To Allocate memory 8"錯誤如何解決的相關(guān)資料,需要的朋友可以參考下2017-03-03
android 對話框彈出位置和透明度的設(shè)置具體實現(xiàn)方法
在android中我們經(jīng)常會用AlertDialog來顯示對話框。通過這個對話框是顯示在屏幕中心的。但在某些程序中,要求對話框可以顯示在不同的位置。2013-07-07

