[Android]開源中國源碼分析之二---DrawerLayout

来源:http://www.cnblogs.com/xiaomoxian/archive/2016/02/27/5222185.html
-Advertisement-
Play Games

從啟動界面到主界面之後的效果如圖所示,採用的是v4包下的DrawerLayout, activity_main.xml文件如下: ...


從啟動界面到主界面之後的效果如圖所示,採用的是v4包下的DrawerLayout, activity_main.xml文件如下:

777

<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout
    android:id="@+id/drawer_layout"
    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="net.oschina.app.ui.MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <FrameLayout
            android:id="@+id/realtabcontent"
            android:layout_width="match_parent"
            android:layout_height="0dip"
            android:layout_weight="1"/>
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/windows_bg">
            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="4dip">
                <net.oschina.app.widget.MyFragmentTabHost
                    android:id="@android:id/tabhost"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="4dip"/>
                <View
                    android:layout_width="match_parent"
                    android:layout_height="1px"
                    android:background="?attr/lineColor"/>
            </RelativeLayout>
            <!-- 快速操作按鈕 -->
            <ImageView
                android:id="@+id/quick_option_iv"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:contentDescription="@null"
                android:src="@drawable/btn_quickoption_selector"/>
        </FrameLayout>
    </LinearLayout>
    <!-- 左側側滑菜單 -->
    <fragment
        android:id="@+id/navigation_drawer"
        android:name="net.oschina.app.ui.NavigationDrawerFragment"
        android:layout_width="@dimen/navigation_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        tools:layout="@layout/fragment_navigation_drawer"/>
</android.support.v4.widget.DrawerLayout>

側邊欄佈局fragment_navigation_drawer.xml的定義:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="?attr/layout_bg_normal" >	
    <net.oschina.app.widget.CustomerScrollView
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1">       
        <include layout="@layout/fragment_navigation_drawer_items"/>      
    </net.oschina.app.widget.CustomerScrollView >
    <include layout="@layout/fragment_navigation_drawer_foot"/>  
</LinearLayout>

fragment_navigation_drawer_items.xml和fragment_navigation_drawer_foot.xml的佈局比較簡單,不再贅述。

主要介紹自定義控制項CustomerScollView,繼承了ScrollView:

package net.oschina.app.widget;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.widget.ScrollView;
/**
 * 可以拖動的ScrollView
 *
 */
public class CustomerScrollView extends ScrollView {
	private static final int size = 4;
	private View inner;
	private float y;
	private Rect normal = new Rect();
	public CustomerScrollView(Context context) {
		super(context);
	}
	public CustomerScrollView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}
	@Override
	protected void onFinishInflate() {
		if (getChildCount() > 0) {
			inner = getChildAt(0);
		}
	}
	@SuppressLint("ClickableViewAccessibility")
	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		if (inner == null) {
			return super.onTouchEvent(ev);
		} else {
			commOnTouchEvent(ev);
		}
		return super.onTouchEvent(ev);
	}
	public void commOnTouchEvent(MotionEvent ev) {
		int action = ev.getAction();
		switch (action) {
		case MotionEvent.ACTION_DOWN:
			y = ev.getY();
			break;
		case MotionEvent.ACTION_UP:
			if (isNeedAnimation()) {
				// Log.v("mlguitar", "will up and animation");
				animation();
			}
			break;
		case MotionEvent.ACTION_MOVE:
			final float preY = y;
			float nowY = ev.getY();
			/**
			 * size=4 表示 拖動的距離為屏幕的高度的1/4
			 */
			int deltaY = (int) (preY - nowY) / size;
			// 滾動
			// scrollBy(0, deltaY);
			y = nowY;
			if (isNeedMove()) {
				if (normal.isEmpty()) {
					normal.set(inner.getLeft(), inner.getTop(),
							inner.getRight(), inner.getBottom());
					return;
				}
				int yy = inner.getTop() - deltaY;
				// 移動佈局
				inner.layout(inner.getLeft(), yy, inner.getRight(),
						inner.getBottom() - deltaY);
			}
			break;
		default:
			break;
		}
	}
	public void animation() {
		TranslateAnimation ta = new TranslateAnimation(0, 0, inner.getTop(),
				normal.top);
		ta.setDuration(200);
		inner.startAnimation(ta);
		inner.layout(normal.left, normal.top, normal.right, normal.bottom);
		normal.setEmpty();
	}
	public boolean isNeedAnimation() {
		return !normal.isEmpty();
	}
	public boolean isNeedMove() {
		int offset = inner.getMeasuredHeight() - getHeight();
		int scrollY = getScrollY();
		if (scrollY == 0 || scrollY == offset) {
			return true;
		}
		return false;
	}
}

再來看看效果:

jdfw

可以看到向上滑動的時候,會有明顯回彈的效果。

oschina客戶端滑動菜單的View的佈局使用了可以拖拽的ScrollView,類文件為CustomerScrollView。

  • 拖拽的目標是ScrollView內的菜單的佈局View,所以在CustomerScrollView內的onFinishInflate()函數中首先通過getChildAt(0)來獲取菜單佈局的View,這就是第一步的目標是獲取要拖拽的對象。onFinishInflate()載入完view,這裡的View指的就是源碼中<include layout="@layout/fragment_navigation_drawer_items"/>載入的佈局文件。
  • 拖拽的過程實際上是一個“按下-移動-抬起”的過程,因此要重寫onTouchEvent(MotionEvent ev),其中移動過程實際上是將菜單view按照移動的方向和距離,怎麼實現這個功能呢?源碼中最關鍵的就是這行代碼inner.layout(inner.getLeft(), yy, inner.getRight(),inner.getBottom() - deltaY);這個方法四個參數都是inner相對其父控制項ScrollView的坐標原點而言的。不是很瞭解的,可以專門查查坐標的相關知識。
  • 當手指抬起也就是MotionEvent.ACTION_UP事件發生時,將拖拽後的view恢復移動到原來位置,移動過程附加了一個動畫,由於移動實際上是位置發生了變化,因此用到了TranslateAnimation,因為是上下拖拽,所以X的起始和終止坐標都是0,Y的起始和終止坐標至於為什麼那麼寫,相信看完博客應該就會明白了。那麼問題來了,要自動移動回去,那麼觸發的時機在MotionEvent.ACTION_UP中,原來的位置怎麼保存,因為移動時需要左上右下四個參數,因此在CustomerScrollView中我們看到了這樣一個變數private Rect normal = new Rect();通過normal.set(inner.getLeft(), inner.getTop(),inner.getRight(), inner.getBottom());方法記錄菜單view的初始化位置。
  • 經過仔細揣摩發現scrollY == 0這個條件實際上是滾動到了最頂部的時候,而scrollY == offset是滾動到最底部的時候,兩個條件滿足其中一個都可以實現拖拽的效果。int offset = inner.getMeasuredHeight() - getHeight();相當於本身的身高減去實際能看到的身高就等於沒有看到的身高部分。
//是否需要移動
public boolean isNeedMove() {
   int offset = inner.getMeasuredHeight() - getHeight();
   int scrollY = getScrollY();
    if (scrollY == 0 || scrollY == offset) {
         return true;
          }
   return false;
}
  • 為什麼源碼中需要isNeedAnimation()這個函數呢?因為恢復到原來位置也用到了inner.layout(normal.left, normal.top, normal.right, normal.bottom);,因此normal首先必須要有四個參數值。而這個normal只有滿足上面的條件後才有值的。
  • 為什麼在拖拽發生又恢復到原來位置後,要把這個normal.setEmpty();置空呢?它的意圖是什麼?仔細想來,發現這個normal的set左上右下四個值時,是在滿足2.4兩種條件之一就會有具體值的。因此這個normal就會有兩種不同的Rect.頂部的時候左上右下四個值分別為(0,0,實際菜單的寬度240dp,菜單的實際測量高度)而滾動到最底部的時候左上右下四個值分別為(0,負的【菜單的實際高度減去屏幕的高度】,實際菜單的寬度240dp,屏幕的高度),因此需要清空。

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 問題:IE8/9不支持Array.indexOf 解決方案 if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(elt /*, from*/) { var len = this.length >>> 0; var fr
  • 1、CSS 簡介 CSS 指層疊樣式表 (Cascading Style Sheets),是一種用來表現 HTML 文檔樣式的語言,樣式定義如何顯示 HTML 元素,是能夠真正做到網頁表現與結構分離的一種樣式設計語言。樣式通常存儲在樣式表中,外部樣式表通常存儲在 CSS 文件中,多個樣式定義可層疊為
  • 這是因為 app.use(function * (){ 語句中有一個 * ,這種方式被稱為generator functions ,一般寫作function *(){...} 的形式,在此類function 中可以支持ES6的一種yield概念。 為了保證這種新型的方法可以編譯通過,在運行node 
  • This application's application-identifier entitlement does not match that of the installed application. These values must match for an upgrade to be a
  • 第一步、首先在你項目中創建一個包存放支持下拉刷新和上拉載入的類: 第二步、需要把兩個動畫導入進來,實現180度旋轉與360度旋轉: 第三步、需要把支持的下拉與上拉顯示的隱藏載入佈局給導入進來 第四步、需要添加strings.xml與colors.xml文件的內容添加到項目裡面: strings.xm
  • 分類:C#、Android、VS2015; 創建日期:2016-02-27 一、簡介 這一節演示如何利用以非同步方式(async、await)訪問SQLite資料庫。 二、示例4運行截圖 下麵左圖為初始頁面,右圖為單擊【創建資料庫】按鈕後的結果。 下麵左圖為單擊【添加單行】按鈕的結果,右圖為單擊【添加...
  • 近期因為項目的需要,研究了一下Android文件下載進度顯示的功能實現,接下來就和大家一起分享學習一下,希望對廣大初學者有幫助。 先上效果圖: 上方的藍色進度條,會根據文件下載量的百分比進行載入,中部的文本控制項用來現在文件下載的百分比,最下方的ImageView用來展示下載好的文件,項目的目的就是動
  • 作者: "@gzdaijie" 本文為作者原創,轉載請註明出處:http://www.cnblogs.com/gzdaijie/p/5222191.html 1.寫在前面 Android提供了豐富的 函數,本文介紹最常用的8種對話框的使用方法,包括普通(包含提示消息和按鈕)、列表、單選、多選、等待、
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...