Dialog源碼學習筆記

Dialog源碼學習筆記

[TOC] (簡書這個不支持嗎?)

Dialog源碼學習筆記Dialog中值得學習之-sendXXMessage
AlertController代碼分析記錄
Context.obtainStyledAttributes詳解

Dialog中值得學習之-sendXXMessage

在Dialog源碼中,dialog的顯示與隱藏是通過mWindowManager.addView/removeViewImmediate來實現的,并且當dialog設置了

dialog.setOnShowListener();
dialog.setOnDismissListener();
dialog.setOnCancelListener();

的時候,當dialog顯示隱藏的時候都會回調給相應的listener的,是如何回調過去的呢?
本質上還是調用各自的方法:

private static final class ListenersHandler extends Handler {
 private WeakReference<DialogInterface> mDialog;

 public ListenersHandler(Dialog dialog) {
     mDialog = new WeakReference<DialogInterface>(dialog);
 }

 @Override
 public void handleMessage(Message msg) {
     switch (msg.what) {
         case DISMISS:
             ((OnDismissListener) msg.obj).onDismiss(mDialog.get());
             break;
         case CANCEL:
             ((OnCancelListener) msg.obj).onCancel(mDialog.get());
             break;
         case SHOW:
             ((OnShowListener) msg.obj).onShow(mDialog.get());
             break;
     }
 }
}

這里中間用Handler和Message去處理listener的回調,這種思路挺贊的。
整體流程就是:
1、setOnShowListener的時候會把OnShowListener對象賦值給Message,并且通過mListenersHandler返回給mShowMessage,這個時候mShowMessage的obj就是該listener了。

public void setOnShowListener(OnShowListener listener) {
        if (listener != null) {
            mShowMessage = mListenersHandler.obtainMessage(SHOW, listener);
        } else {
            mShowMessage = null;
        }
    }

2、當dialog調用show的時候,會執行sendShowMessage(),然后再讓mDismissMessage.sendToTarget()傳遞給mListenersHandler的handleMessage去執行。

public void show() {
        //.......省略代碼
        try {
            mWindowManager.addView(mDecor, l);
            mShowing = true;
    
            sendShowMessage();
        } finally {
        }
    }

private void sendDismissMessage() {
        if (mDismissMessage != null) {
            // Obtain a new message so this dialog can be re-used
            Message.obtain(mDismissMessage).sendToTarget();
        }
    }
private void sendShowMessage() {
    if (mShowMessage != null) {
        // Obtain a new message so this dialog can be re-used
        Message.obtain(mShowMessage).sendToTarget();
    }
}

這里再插一句:為什么一定要用Message.obtain(mShowMessage)呢?不直接mShowMessage.sendToTarget()呢?
原因在內部調用了obtain,這個obtain里面實現了避免重復創建新的Message對象的機制。減少內存的消耗!這個是sdk的開發者思考過的問題,message在應用中使用的頻率特別高,所以為了減少內存消耗出此策略,點贊!

public static Message obtain(Message orig) {
        Message m = obtain();
        m.what = orig.what;
        m.arg1 = orig.arg1;
        m.arg2 = orig.arg2;
        m.obj = orig.obj;
        m.replyTo = orig.replyTo;
        m.sendingUid = orig.sendingUid;
        if (orig.data != null) {
            m.data = new Bundle(orig.data);
        }
        m.target = orig.target;
        m.callback = orig.callback;

        return m;
    }
    
    /**
     * Return a new Message instance from the global pool. Allows us to
     * avoid allocating new objects in many cases.
     */
    public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; // clear in-use flag
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }

總結一下:如果要我去實現一個listener的回調,大部分情況下是直接聲明一個listener的變量,什么地方需要執行該listener的回調,什么地方就手動調用一下。
這里用

    private Message mCancelMessage;
    private Message mDismissMessage;
    private Message mShowMessage;

替代了,感覺來說會使代碼更合理些。可能具體有什么好處,暫時參悟不出來,如果有感興趣的人看到了這篇筆記,可以給我回復一起探討下!

AlertController代碼分析記錄

AlertDialog extends Dialog implements DialogInterface {
    private AlertController mAlert;
    public static class Builder {
        private final AlertController.AlertParams P;
    }
}

首先AlertDialog的這個類的結構大家是知道的,使用了Builder設計模式。
在Dialog的show函數中,

if (!mCreated) {
    dispatchOnCreate(null);
}
mDecor = mWindow.getDecorView();
mWindowManager.addView(mDecor, l);

會執行onCreate函數創建view視圖,然后通過windowManager添加視圖,這樣一個彈窗就顯示在了界面中。

AlertDialog中的oncreate中調用的是AlertController.installContent函數

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mAlert.installContent();
}

http://grepcode.com/中可以找到AlertController的源碼

public void More ...installContent() {
232         /* We use a custom title so never request a window title */
233         mWindow.requestFeature(Window.FEATURE_NO_TITLE);
234         int contentView = selectContentView();
235         mWindow.setContentView(contentView);
236         setupView();
237         setupDecor();
238     }
239 
240     private int More ...selectContentView() {
241         if (mButtonPanelSideLayout == 0) {
242             return mAlertDialogLayout;
243         }
244         if (mButtonPanelLayoutHint == AlertDialog.LAYOUT_HINT_SIDE) {
245             return mButtonPanelSideLayout;
246         }
247         // TODO: use layout hint side for long messages/lists
248         return mAlertDialogLayout;
249     }

如果沒有給AlertDialog設置自定義view,則使用一個默認的mAlertDialogLayout,這個默認的

 TypedArray a = context.obtainStyledAttributes(null,  com.android.internal.R.styleable.AlertDialog, com.android.internal.R.attr.alertDialogStyle, 0);
 mAlertDialogLayout = a.getResourceId(com.android.internal.R.styleable.AlertDialog_layout,  com.android.internal.R.layout.alert_dialog);

com.android.internal.R.layout.alert_dialog的文件可以在sdk中找到,太長了,大概略讀了下,發現了里面有個

<com.android.internal.widget.DialogTitle android:id="@+id/alertTitle"
                style="?android:attr/textAppearanceLarge"
                android:singleLine="true"
                android:ellipsize="end"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textAlignment="viewStart" />

Context.obtainStyledAttributes詳解

這個DialogTitle是個什么?在grepcode中可以找到

public class More ...DialogTitle extends TextView {
31
32    public More ...DialogTitle(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
33        super(context, attrs, defStyleAttr, defStyleRes);
34    }
47    //......省略構造函數
48    @Override
49    protected void More ...onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
50        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
51
52        final Layout layout = getLayout();
53        if (layout != null) {
54            final int lineCount = layout.getLineCount();
55            if (lineCount > 0) {
56                final int ellipsisCount = layout.getEllipsisCount(lineCount - 1);
57                if (ellipsisCount > 0) {
58                    setSingleLine(false);
59                    setMaxLines(2);
60
61                    final TypedArray a = mContext.obtainStyledAttributes(null,
62                            android.R.styleable.TextAppearance, android.R.attr.textAppearanceMedium,
63                            android.R.style.TextAppearance_Medium);
64                    final int textSize = a.getDimensionPixelSize(
65                            android.R.styleable.TextAppearance_textSize, 0);
66                    if (textSize != 0) {
67                        // textSize is already expressed in pixels
68                        setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
69                    }
70                    a.recycle();
71
72                    super.onMeasure(widthMeasureSpec, heightMeasureSpec);      
73                }
74            }
75        }
76    }
77}

仔細分析這段代碼,這段代碼主要的用途就是讓dialog的title最多顯示兩行,且如果是兩行,字體大小由原來的大號變成中號。
知識點:
如果要計算textview的行數,可以自定義這個textview,并且在onMeasure方法中處理。因為onMeasure函數是在textview真正要開始布局的時候會執行,并且很多情況下可能會執行多次。

        final Layout layout = getLayout();
        if (layout != null) {
            final int lineCount = layout.getLineCount();
            if (lineCount > 0) {

這里可以跟進getLayout的源碼,這個layout必須判空,注釋里說當這個textview的text或者width最近修改了,這個可能會為空的。
之前在項目開發中通過textPaint的各種手段計算出textview的行數,今天又發現了另外一種方法。

之前一直沒有對mContext.obtainStyledAttributes做好好的分析,自己自定義view的時候一般用一些模板代碼套用。

final TypedArray a = mContext.obtainStyledAttributes(
 null,
 android.R.styleable.TextAppearance, 
 android.R.attr.textAppearanceMedium,
 android.R.style.TextAppearance_Medium);

第一個參數是xml文件中的定義的屬性集(理解為鍵值對),
第二個參數是R.styleable.TextAppearance即為要取出typeArray的目標屬性(理解為鍵),
第三個是系統當前theme下默認的屬性集(理解為建值對),
第四個是備用的一個style(理解為鍵值對),當第三個屬性 找不到或者為0, 可以直接指定某個style。

第二個參數android.R.styleable.TextAppearance在源碼的attrs.xml的

<declare-styleable name="TextAppearance">
        <!-- Text color. -->
        <attr name="textColor" />
        <!-- Size of the text. Recommended dimension type for text is "sp" for scaled-pixels (example: 15sp). -->
        <attr name="textSize" />
        <!-- Style (bold, italic, bolditalic) for the text. -->
        <attr name="textStyle" />
        <!-- Typeface (normal, sans, serif, monospace) for the text. -->
        <attr name="typeface" />
        <!-- Font family (named by string) for the text. -->
        <attr name="fontFamily" />
        <!-- Color of the text selection highlight. -->
        <attr name="textColorHighlight" />
        <!-- Color of the hint text. -->
        <attr name="textColorHint" />
        <!-- Color of the links. -->
        <attr name="textColorLink" />
        <!-- Present the text in ALL CAPS. This may use a small-caps form when available. -->
        <attr name="textAllCaps" format="boolean" />

第三個參數android.R.attr.textAppearanceMedium在源碼的attrs.xml的

<declare-styleable name="Theme">
<attr name="textAppearanceMedium" format="reference" />
</declare-styleable>

這里的格式是format="reference"即需要引用其它的屬性,然后我在themes.xml中找到了該引用的地方:

<style name="Theme">
<item name="textAppearanceMedium">@style/TextAppearance.Medium</item>
</style>
<style name="Theme.Dialog">
<item name="textAppearanceMedium">@style/TextAppearance.Medium</item>
</style>

發現這里有兩個地方是textAppearanceMedium,但是一個是Theme,一個是Theme.Dialog,說明不同的theme 指向不同的style,雖然這里還是指向同一個style。。。

第四個參數在源碼的styles.xml中

<style name="TextAppearance.Medium">
        <item name="textSize">18sp</item>
    </style>

【摘抄】幾個參數的優先級如下示:“>大于符號” xml里的顯示定義如 bar:attr1="12345">xml里的style定義如:android:style=@style/test>當前theme>備用Style。android系統會按照優先級依次去查找。大家有興趣可以自己做個實驗看一看。

上述解釋需要好好體會一下,總體來說

final TypedArray a = mContext.obtainStyledAttributes(
 null,
 android.R.styleable.TextAppearance, 
 android.R.attr.textAppearanceMedium,
 android.R.style.TextAppearance_Medium);

這段代碼就是獲取一個屬性值,把android.R.styleable.TextAppearance里的textSize的屬性用@style/TextAppearance.Medium的

<item name="textSize">18sp</item>

來代替。因為第三個參數是表示系統當前theme下默認的屬性集是這個android.R.attr.textAppearanceMedium,這里做法僅僅是代碼中臨時調整,并不會真的改變當前theme下的默認屬性集,當前theme是在activity或application中配置的。

一般自定義view獲取屬性模板代碼

TypedArray typedArray=context.obtainStyledAttributes(attrs, R.styleable.button); 
    this.setTextSize(typedArray.getDimension(R.styleable.button_textSize, 15)); 
    typedArray.recycle();

我們通過下面的代碼

final int textSize = a.getDimensionPixelSize(
android.R.styleable.TextAppearance_textSize, 0);

取出來的textSize是px的單位,所以給textview設置的時候要指定單位。
android-getTextSize返回值是以像素(px)為單位的,setTextSize()以sp為單位
使用如下代碼時,發現字號不會變大,反而會變小:
size = (int) mText.getTextSize() + 1;
mText.setTextSize(size);
后來發現getTextSize返回值是以像素(px)為單位的,而setTextSize()是以sp為單位的,兩者單位不一致才造成這樣的結果。

這里可以用setTextSize()的另外一種形式,可以指定單位:
setTextSize(int unit, int size)
TypedValue.COMPLEX_UNIT_PX : Pixels
TypedValue.COMPLEX_UNIT_SP : Scaled Pixels
TypedValue.COMPLEX_UNIT_DIP : Device Independent Pixels

下面這樣就正常了:
size = (int) mText.getTextSize() + 1;
mText.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,155評論 25 708
  • ¥開啟¥ 【iAPP實現進入界面執行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開一個線程,因...
    小菜c閱讀 6,510評論 0 17
  • afinalAfinal是一個android的ioc,orm框架 https://github.com/yangf...
    passiontim閱讀 15,509評論 2 45
  • HTML表單作用 HTML表單是什么? 簡單來說,HTML表單就是:能夠讓用戶輸入具體內容的信息表,比如郵箱注冊 ...
    NathanYangcn閱讀 822評論 0 1
  • 一曲梵音 穿梭在霧霾的雨絲中 一條木魚 游向佛前的宮殿 凡塵袈裟抑制俗子欲望 般若文字 盛滿慈悲的缽 蕓蕓眾生 我...
    易文畫影閱讀 122評論 0 4