标签:
各位童鞋,对于Android而言,离开Activity,基本上就无从谈起开发,那么亲们对于Activity的实现原理熟悉么?反正我在没有看源码之前是不熟悉的,下面,咱们一起按照老规矩,一起来看一下Activity的源码吧。这一篇文章主要讲解的是Activity如何对对话框Dialog进行实现统一管理的。
首先我们看到的是这样一个类:
private static class ManagedDialog { Dialog mDialog; Bundle mArgs; } private SparseArray<ManagedDialog> mManagedDialogs;
接下来我们需要看的一个方法是restoreManagedDialogs,也就是说是恢复被管理的Dialog的状态。
private void restoreManagedDialogs(Bundle savedInstanceState) { final Bundle b = savedInstanceState.getBundle(SAVED_DIALOGS_TAG); if (b == null) { return; } final int[] ids = b.getIntArray(SAVED_DIALOG_IDS_KEY); final int numDialogs = ids.length; mManagedDialogs = new SparseArray<ManagedDialog>(numDialogs); for (int i = 0; i < numDialogs; i++) { final Integer dialogId = ids[i]; Bundle dialogState = b.getBundle(savedDialogKeyFor(dialogId)); if (dialogState != null) { final ManagedDialog md = new ManagedDialog(); md.mArgs = b.getBundle(savedDialogArgsKeyFor(dialogId)); md.mDialog = createDialog(dialogId, dialogState, md.mArgs); if (md.mDialog != null) { mManagedDialogs.put(dialogId, md); onPrepareDialog(dialogId, md.mDialog, md.mArgs); md.mDialog.onRestoreInstanceState(dialogState); } } } }首先获取Bundle的对象,获取Bundle对象中存储的Dialog的id的数组。创建SparseArray<ManagedDialog>列表对象的集合。通过for循环迭代,通过存储的数据,创建新的Dialog,进行恢复。
创建Dialog会回调到下面的方法体中来:
private Dialog createDialog(Integer dialogId, Bundle state, Bundle args) { final Dialog dialog = onCreateDialog(dialogId, args); if (dialog == null) { return null; } dialog.dispatchOnCreate(state); return dialog; }我们会发现,实际在Activity的源码中,onCreateDialog内部是空的,也就是说,我们需要自己定义的Activity中重写当前的方法,创建我们的Dialog,然后会在这里触发到Dialog的onCreate方法。
有了前面的恢复,就必然有现在的存储Dialog的状态的数据:
private void saveManagedDialogs(Bundle outState) { if (mManagedDialogs == null) { return; } final int numDialogs = mManagedDialogs.size(); if (numDialogs == 0) { return; } Bundle dialogState = new Bundle(); int[] ids = new int[mManagedDialogs.size()]; for (int i = 0; i < numDialogs; i++) { final int key = mManagedDialogs.keyAt(i); ids[i] = key; final ManagedDialog md = mManagedDialogs.valueAt(i); dialogState.putBundle(savedDialogKeyFor(key), md.mDialog.onSaveInstanceState()); if (md.mArgs != null) { dialogState.putBundle(savedDialogArgsKeyFor(key), md.mArgs); } } dialogState.putIntArray(SAVED_DIALOG_IDS_KEY, ids); outState.putBundle(SAVED_DIALOGS_TAG, dialogState); }
if (mManagedDialogs != null) { final int numDialogs = mManagedDialogs.size(); for (int i = 0; i < numDialogs; i++) { final ManagedDialog md = mManagedDialogs.valueAt(i); if (md.mDialog.isShowing()) { md.mDialog.dismiss(); } } mManagedDialogs = null; }
关于Activity中的Dialog的管理就讲到这里,希望大家能够有所收获。
Android中Activity源码中是如何对对话框Dialog进行处理的
标签:
原文地址:http://blog.csdn.net/zhangjiaofa/article/details/42262417