墨香帶你學Launcher之(七)--小部件的加載、添加以及大小調節

上一章墨香帶你學Launcher之(六)--拖拽咱們介紹了Launcher的拖拽過程,涉及到的範圍比較廣,包括圖標的拖拽,桌面上CellLayout的拖拽,小部件的拖拽,以及跨不一樣部件的拖拽,設計思想很是巧妙,不過整個流程相對也比較好掌握,只要跟着上一章的流程本身多跟蹤幾遍基本就熟悉了。按照計劃本章咱們繼續學習Launcher的Widget的加載、添加以及Widget的大小調節。javascript

Widget的數據加載

其實咱們在第二章墨香帶你學Launcher之(二)-數據加載流程介紹過Widget數據的加載,相對只是簡單的作了介紹,下面咱們稍微講的詳細點。java

咱們知道Widget的數據加載開始在LauncherModel中的updateWidgetsModel方法中,咱們看下代碼:git

void updateWidgetsModel(boolean refresh) {
        PackageManager packageManager = mApp.getContext().getPackageManager();
        final ArrayList<Object> widgetsAndShortcuts = new ArrayList<Object>();
        widgetsAndShortcuts.addAll(getWidgetProviders(mApp.getContext(), refresh));
        Intent shortcutsIntent = new Intent(Intent.ACTION_CREATE_SHORTCUT);
        widgetsAndShortcuts.addAll(packageManager.queryIntentActivities(shortcutsIntent, 0));
        mBgWidgetsModel.setWidgetsAndShortcuts(widgetsAndShortcuts);
    }複製代碼

上面代碼咱們能夠看到是經過調用getWidgetProviders(mApp.getContext(), refresh)方法來獲取全部Widget的,代碼:github

public static List<LauncherAppWidgetProviderInfo> getWidgetProviders(Context context,
                                                                         boolean refresh) {
        ArrayList<LauncherAppWidgetProviderInfo> results =
                new ArrayList<LauncherAppWidgetProviderInfo>();
        try {
            synchronized (sBgLock) {
                if (sBgWidgetProviders == null || refresh) {
                    HashMap<ComponentKey, LauncherAppWidgetProviderInfo> tmpWidgetProviders
                            = new HashMap<>();
                    AppWidgetManagerCompat wm = AppWidgetManagerCompat.getInstance(context);
                    LauncherAppWidgetProviderInfo info;

                    List<AppWidgetProviderInfo> widgets = wm.getAllProviders();
                    for (AppWidgetProviderInfo pInfo : widgets) {
                        info = LauncherAppWidgetProviderInfo.fromProviderInfo(context, pInfo);
                        UserHandleCompat user = wm.getUser(info);
                        tmpWidgetProviders.put(new ComponentKey(info.provider, user), info);
                    }

                    Collection<CustomAppWidget> customWidgets = Launcher.getCustomAppWidgets().values();
                    for (CustomAppWidget widget : customWidgets) {
                        info = new LauncherAppWidgetProviderInfo(context, widget);
                        UserHandleCompat user = wm.getUser(info);
                        tmpWidgetProviders.put(new ComponentKey(info.provider, user), info);
                    }
                    // Replace the global list at the very end, so that if there is an exception,
                    // previously loaded provider list is used.
                    sBgWidgetProviders = tmpWidgetProviders;
                }
                results.addAll(sBgWidgetProviders.values());
                return results;
            }
        } catch (Exception e) {
            ...    
        }
    }複製代碼

咱們看到首先是初始化AppWidgetManagerCompat,咱們以前介紹過帶有Compat的是兼容組件,咱們看看是怎麼兼容的,spring

咱們下面代碼:微信

public static AppWidgetManagerCompat getInstance(Context context) {
        synchronized (sInstanceLock) {
            if (sInstance == null) {
                if (Utilities.ATLEAST_LOLLIPOP) {
                    sInstance = new AppWidgetManagerCompatVL(context.getApplicationContext());
                } else {
                    sInstance = new AppWidgetManagerCompatV16(context.getApplicationContext());
                }
            }
            return sInstance;
        }
    }複製代碼

咱們能夠看到AppWidgetManagerCompat的初始化有兩個,一個是當Api版本高於21(包含21)時,用AppWidgetManagerCompatVL,低於21時用AppWidgetManagerCompatV16,這兩個有什麼不一樣,咱們下面分析。app

下面咱們看如何獲取Widget列表對象:異步

List<AppWidgetProviderInfo> widgets = wm.getAllProviders();複製代碼

getAllProviders()方法是一個抽象方法,因此咱們看哪裏進行了複寫,ide

能夠看到仍是上面兩個兼容類複寫了該方法,咱們看這個兩個類中作了什麼處理,先看V16中的:函數

@Override
    public List<AppWidgetProviderInfo> getAllProviders() {
        return mAppWidgetManager.getInstalledProviders();
    }複製代碼

咱們再看mAppWidgetManager這個是在哪裏初始化,

@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    @Override
    public boolean bindAppWidgetIdIfAllowed(int appWidgetId, AppWidgetProviderInfo info,
            Bundle options) {
        if (Utilities.ATLEAST_JB_MR1) {
            return mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, info.provider, options);
        } else {
            return mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId, info.provider);
        }
    }複製代碼

裏面有個if語句,咱們能夠看到當Api大於等於17時,調用第一個進行初始化,不然調用第二個方法進行初始化,這就是對不一樣手機版本作的兼容。在咱們寫App的時候若是遇到類似狀況也能夠這麼處理。

咱們再看一下VL中的getAllProviders()方法:

@Override
    public List<AppWidgetProviderInfo> getAllProviders() {
        ArrayList<AppWidgetProviderInfo> providers = new ArrayList<AppWidgetProviderInfo>();
        for (UserHandle user : mUserManager.getUserProfiles()) {
            providers.addAll(mAppWidgetManager.getInstalledProvidersForProfile(user));
        }
        return providers;
    }複製代碼

和V16中的不同了,這裏面是經過for循環來獲取的,其中有個UserHandle,那麼在源碼中給出的解釋是設備中的每一個用戶,我的理解應該是每一個應用,每一個應用會有0-N個Widget,也就是從每一個應用中獲取每一個應用的Widget列表。這樣for循環就能夠獲取整個手機中全部應用的widget列表了。

再回到上面getWidgetProviders方法的代碼中,咱們接着看,接着for循環AppWidgetProviderInfo列表信息,重構LauncherAppWidgetProviderInfo對象,這裏有點怪,爲啥有了AppWidgetProviderInfo對象還要重構一個LauncherAppWidgetProviderInfo對象,咱們知道在寫插件的時候每一個Widget都會有一個類繼承AppWidgetProvider,這樣纔會有一個插件,所以咱們知道AppWidgetProviderInfo對象確定是AppWidgetProvider的對象,那麼LauncherAppWidgetProviderInfo是什麼,咱們接着看能不能找到答案,LauncherAppWidgetProviderInfo的初始化時經過

LauncherAppWidgetProviderInfo.fromProviderInfo(context, pInfo);複製代碼

方法進行初始化的,咱們再看LauncherAppWidgetProviderInfo又繼承AppWidgetProviderInfo,愈來愈怪,咱們接着看fromProviderInfo(context, pInfo)方法:

public static LauncherAppWidgetProviderInfo fromProviderInfo(Context context,
            AppWidgetProviderInfo info) {
        Parcel p = Parcel.obtain();
        info.writeToParcel(p, 0);
        p.setDataPosition(0);
        LauncherAppWidgetProviderInfo lawpi = new LauncherAppWidgetProviderInfo(p);
        p.recycle();
        return lawpi;
    }複製代碼

咱們看到最後是經過new LauncherAppWidgetProviderInfo來生成一個LauncherAppWidgetProviderInfo對象,那麼這個對象構造函數中有什麼:

public LauncherAppWidgetProviderInfo(Parcel in) {
        super(in);
        initSpans();
    }複製代碼

這個構造函數調用了initSpans方法,咱們接着追尋:

private void initSpans() {
        LauncherAppState app = LauncherAppState.getInstance();
        InvariantDeviceProfile idp = app.getInvariantDeviceProfile();

        // We only care out the cell size, which is independent of the the layout direction.
        Rect paddingLand = idp.landscapeProfile.getWorkspacePadding(false /* isLayoutRtl */);
        Rect paddingPort = idp.portraitProfile.getWorkspacePadding(false /* isLayoutRtl */);

        // Always assume we're working with the smallest span to make sure we
        // reserve enough space in both orientations.
        float smallestCellWidth = DeviceProfile.calculateCellWidth(Math.min(
                idp.landscapeProfile.widthPx - paddingLand.left - paddingLand.right,
                idp.portraitProfile.widthPx - paddingPort.left - paddingPort.right),
                idp.numColumns);
        float smallestCellHeight = DeviceProfile.calculateCellWidth(Math.min(
                idp.landscapeProfile.heightPx - paddingLand.top - paddingLand.bottom,
                idp.portraitProfile.heightPx - paddingPort.top - paddingPort.bottom),
                idp.numRows);

        // We want to account for the extra amount of padding that we are adding to the widget
        // to ensure that it gets the full amount of space that it has requested.
        Rect widgetPadding = AppWidgetHostView.getDefaultPaddingForWidget(
                app.getContext(), provider, null);
        spanX = Math.max(1, (int) Math.ceil(
                        (minWidth + widgetPadding.left + widgetPadding.right) / smallestCellWidth));
        spanY = Math.max(1, (int) Math.ceil(
                (minHeight + widgetPadding.top + widgetPadding.bottom) / smallestCellHeight));

        minSpanX = Math.max(1, (int) Math.ceil(
                (minResizeWidth + widgetPadding.left + widgetPadding.right) / smallestCellWidth));
        minSpanY = Math.max(1, (int) Math.ceil(
                (minResizeHeight + widgetPadding.top + widgetPadding.bottom) / smallestCellHeight));
    }複製代碼

這段代碼也不難,是爲了算四個參數:spanX、spanY、minSpanX、minSpanY,看過我前面博客的都知道這個spanX和spanY參數是什麼,其實這個LauncherAppWidgetProviderInfo對象比系統自帶的AppWidgetProviderInfo帶有的就是多了這幾個參數,也就是方便咱們添加到桌面是計算佔用位置。

最後獲得HashMap 這個Widget集合,最後經過

mBgWidgetsModel.setWidgetsAndShortcuts(widgetsAndShortcuts);複製代碼

將這個集合放到WidgetsModel中:

public void setWidgetsAndShortcuts(ArrayList<Object> rawWidgetsShortcuts) {
        ...
        HashMap<String, PackageItemInfo> tmpPackageItemInfos = new HashMap<>();

        // clear the lists.
        ...

        InvariantDeviceProfile idp = LauncherAppState.getInstance().getInvariantDeviceProfile();

        // add and update.
        for (Object o: rawWidgetsShortcuts) {
            String packageName = "";
            UserHandleCompat userHandle = null;
            ComponentName componentName = null;
            if (o instanceof LauncherAppWidgetProviderInfo) {
                LauncherAppWidgetProviderInfo widgetInfo = (LauncherAppWidgetProviderInfo) o;

                // Ensure that all widgets we show can be added on a workspace of this size
                int minSpanX = Math.min(widgetInfo.spanX, widgetInfo.minSpanX);
                int minSpanY = Math.min(widgetInfo.spanY, widgetInfo.minSpanY);
                if (minSpanX <= (int) idp.numColumns &&
                    minSpanY <= (int) idp.numRows) {
                    componentName = widgetInfo.provider;
                    packageName = widgetInfo.provider.getPackageName();
                    userHandle = mAppWidgetMgr.getUser(widgetInfo);
                } else {
                    ...
                    continue;
                }
            } else if (o instanceof ResolveInfo) {
                ResolveInfo resolveInfo = (ResolveInfo) o;
                componentName = new ComponentName(resolveInfo.activityInfo.packageName,
                        resolveInfo.activityInfo.name);
                packageName = resolveInfo.activityInfo.packageName;
                userHandle = UserHandleCompat.myUserHandle();
            }

            if (componentName == null || userHandle == null) {
                ...
                continue;
            }
            ...

            PackageItemInfo pInfo = tmpPackageItemInfos.get(packageName);
            ArrayList<Object> widgetsShortcutsList = mWidgetsList.get(pInfo);
            if (widgetsShortcutsList != null) {
                widgetsShortcutsList.add(o);
            } else {
                widgetsShortcutsList = new ArrayList<>();
                widgetsShortcutsList.add(o);
                pInfo = new PackageItemInfo(packageName);
                mIconCache.getTitleAndIconForApp(packageName, userHandle,
                        true /* userLowResIcon */, pInfo);
                pInfo.titleSectionName = mIndexer.computeSectionName(pInfo.title);
                mWidgetsList.put(pInfo, widgetsShortcutsList);
                tmpPackageItemInfos.put(packageName,  pInfo);
                mPackageItemInfos.add(pInfo);
            }
        }

        // 排序.
        ...
        }
    }複製代碼

在這裏將不一樣應用的Widget放到同一個列表中而後在放到mWidgetsList中,以供應加載Widget列表。接着執行綁定過程,綁定過程咱們在第三章墨香帶你學Launcher之(三)-綁定屏幕、圖標、文件夾和Widget介紹過,可是裏面還有些東西在這裏須要介紹一下,咱們看源碼知道其實Widget是經過適配器放置到WidgetsRecyclerView裏面的,WidgetsRecyclerView是一個RecyclerView,而每一個Widget視圖是一個WidgetCell,那麼WidgetCell是什麼,咱們看WidgetsListAdapter適配器,這個咱們就不詳細介紹了,在裏面的onBindViewHolder方法中對WidgetCell進行了初始化,其中在裏面會調動下面方法:

widget.applyFromAppWidgetProviderInfo(info, mWidgetPreviewLoader);複製代碼

咱們看看這個方法:

public void applyFromAppWidgetProviderInfo(LauncherAppWidgetProviderInfo info,
            WidgetPreviewLoader loader) {

        InvariantDeviceProfile profile =
                LauncherAppState.getInstance().getInvariantDeviceProfile();
        mInfo = info;
        // TODO(hyunyoungs): setup a cache for these labels.
        mWidgetName.setText(AppWidgetManagerCompat.getInstance(getContext()).loadLabel(info));
        int hSpan = Math.min(info.spanX, profile.numColumns);
        int vSpan = Math.min(info.spanY, profile.numRows);
        mWidgetDims.setText(String.format(mDimensionsFormatString, hSpan, vSpan));
        mWidgetPreviewLoader = loader;
    }複製代碼

上面代碼經過mWidgetName.setText顯示名字,經過mWidgetDims.setText顯示大小。最後給mWidgetPreviewLoader賦值,咱們看到這個loader是從WidgetsListAdapter中傳遞進來的,在WidgetsListAdapter中,是經過LauncherAppState.getInstance().getWidgetCache()獲取的,其實這個loader是在LauncherAppState初始化的時候就初始化了。

在WidgetCell初始化後調用了widget.ensurePreview()方法:

public void ensurePreview() {
        ...
        int[] size = getPreviewSize();
        mActiveRequest = mWidgetPreviewLoader.getPreview(mInfo, size[0], size[1], this);
    }複製代碼

在這裏調用mWidgetPreviewLoader.getPreview方法:

public PreviewLoadRequest getPreview(final Object o, int previewWidth,
            int previewHeight, WidgetCell caller) {
        String size = previewWidth + "x" + previewHeight;
        WidgetCacheKey key = getObjectKey(o, size);

        PreviewLoadTask task = new PreviewLoadTask(key, o, previewWidth, previewHeight, caller);
        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        return new PreviewLoadRequest(task);
    }複製代碼

在這裏執行了一個異步任務PreviewLoadTask,咱們看一下這個異步任務,首先看doInBackground方法:

...
preview = generatePreview(launcher, mInfo, unusedBitmap, mPreviewWidth, mPreviewHeight);
...複製代碼

接着看generatePreview方法:

Bitmap generatePreview(Launcher launcher, Object info, Bitmap recycle,
            int previewWidth, int previewHeight) {
        if (info instanceof LauncherAppWidgetProviderInfo) {
            return generateWidgetPreview(launcher, (LauncherAppWidgetProviderInfo) info,
                    previewWidth, recycle, null);
        } else {
            return generateShortcutPreview(launcher,
                    (ResolveInfo) info, previewWidth, previewHeight, recycle);
        }
    }複製代碼

咱們看到是生成一個Bitmap,而後調用generateWidgetPreview生成Bitmap:

public Bitmap generateWidgetPreview(Launcher launcher, LauncherAppWidgetProviderInfo info,
            int maxPreviewWidth, Bitmap preview, int[] preScaledWidthOut) {
        // Load the preview image if possible
        if (maxPreviewWidth < 0) maxPreviewWidth = Integer.MAX_VALUE;

        Drawable drawable = null;
        if (info.previewImage != 0) {
            // 獲取相對應的drawable
            drawable = mManager.loadPreview(info);
            ...
        }

        // Draw the scaled preview into the final bitmap
        int x = (preview.getWidth() - previewWidth) / 2;
        if (widgetPreviewExists) {
            drawable.setBounds(x, 0, x + previewWidth, previewHeight);
            drawable.draw(c);
        } else {
            ...
            for (int i = 0; i < spanX; i++, tx += tileW) {
                float ty = 0;
                for (int j = 0; j < spanY; j++, ty += tileH) {
                    dst.offsetTo(tx, ty);
                    c.drawBitmap(tileBitmap, src, dst, p);
                }
            }
            ...
            try {
                Drawable icon = mutateOnMainThread(mManager.loadIcon(info, mIconCache));
                if (icon != null) {
                    ...
                    icon.draw(c);
                }
            } catch (Resources.NotFoundException e) { }
            c.setBitmap(null);
        }
        int imageHeight = Math.min(preview.getHeight(), previewHeight + mProfileBadgeMargin);
        return mManager.getBadgeBitmap(info, preview, imageHeight);
    }複製代碼

整個過程就是從系統加載出Widget對應的Drawable而後繪製到Bitmap上面返回,而後在onPostExecute方法中將該圖片添加到WidgetCell上面,就顯示到了WidgetCell列表中。整個加載就完成了。

Widget的添加:

咱們以前講過,Widget列表最後是綁定到WidgetsContainerView中的,而咱們將Widget放置到桌面是經過長按拖拽到桌面來完成的,所以咱們能夠知道添加的觸發事件是經過長按事件來觸發的,由於咱們找到WidgetsContainerView中的長按事件:

@Override
    public boolean onLongClick(View v) {

        ...

        boolean status = beginDragging(v);
        if (status && v.getTag() instanceof PendingAddWidgetInfo) {
            WidgetHostViewLoader hostLoader = new WidgetHostViewLoader(mLauncher, v);
            boolean preloadStatus = hostLoader.preloadWidget();
            ...
            mLauncher.getDragController().addDragListener(hostLoader);
        }
        return status;
    }複製代碼

首先調用beginDragging方法:

private boolean beginDragging(View v) {
        if (v instanceof WidgetCell) {
            if (!beginDraggingWidget((WidgetCell) v)) {
                return false;
            }
        } else {
            Log.e(TAG, "Unexpected dragging view: " + v);
        }

        // We don't enter spring-loaded mode if the drag has been cancelled
        if (mLauncher.getDragController().isDragging()) {
            // Go into spring loaded mode (must happen before we startDrag())
            mLauncher.enterSpringLoadedDragMode();
        }

        return true;
    }複製代碼

若是是Widget的視圖(WidgetCell)也就是長按的是Widget佈局則調用beginDraggingWidget方法:

private boolean beginDraggingWidget(WidgetCell v) {
        WidgetImageView image = (WidgetImageView) v.findViewById(R.id.widget_preview);
        ...

        if (createItemInfo instanceof PendingAddWidgetInfo) {
            ...
            Bitmap icon = image.getBitmap();
            float minScale = 1.25f;
            int maxWidth = Math.min((int) (icon.getWidth() * minScale), size[0]);

            ...
            preview = getWidgetPreviewLoader().generateWidgetPreview(mLauncher,
                    createWidgetInfo.info, maxWidth, null, previewSizeBeforeScale);

            ...
            scale = bounds.width() / (float) preview.getWidth();
        } else {
            // shortcut
            ...
        }

        // Don't clip alpha values for the drag outline if we're using the default widget preview
        boolean clipAlpha = !(createItemInfo instanceof PendingAddWidgetInfo &&
                (((PendingAddWidgetInfo) createItemInfo).previewImage == 0));

        // Start the drag
        mLauncher.lockScreenOrientation();
        mLauncher.getWorkspace().onDragStartedWithItem(createItemInfo, preview, clipAlpha);
        mDragController.startDrag(image, preview, this, createItemInfo,
                bounds, DragController.DRAG_ACTION_COPY, scale);

        preview.recycle();
        return true;
    }複製代碼

上面代碼中的generateWidgetPreview方法咱們在上面已經講過了,就是生產WidgetCell圖片的,而後鎖定屏幕旋轉,而後調用onDragStartedWithItem方法:

public void onDragStartedWithItem(PendingAddItemInfo info, Bitmap b, boolean clipAlpha) {
        int[] size = estimateItemSize(info, false);

        // The outline is used to visualize where the item will land if dropped
        mDragOutline = createDragOutline(b, DRAG_BITMAP_PADDING, size[0], size[1], clipAlpha);
    }複製代碼

整個方法在拖拽中講過,就是在workspace中生成一個拖拽view的輪廓邊框,而後調用mDragController.startDrag方法,以後的過程在拖拽章節中有很詳細的講解,因此在此再也不重複了,沒看過拖拽的能夠去看拖拽過程詳解。下面只是個提示過程。

在放置到桌面時會調用onDrop方法,而後調用onDropExternal方法,而後調用addPendingItem方法:

public void addPendingItem(PendingAddItemInfo info, long container, long screenId,
                               int[] cell, int spanX, int spanY) {
        switch (info.itemType) {
            case LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET:
            case LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET:
                int span[] = new int[2];
                span[0] = spanX;
                span[1] = spanY;
                addAppWidgetFromDrop((PendingAddWidgetInfo) info,
                        container, screenId, cell, span);
                break;
            ...
            }
    }複製代碼

若是是Widget則調用addAppWidgetFromDrop方法,而後調用addAppWidgetImpl方法,而後調用completeAddAppWidget方法,最後調用mWorkspace.addInScreen方法就講WidgetCell添加到了桌面上。

Widget的大小調節:

咱們在桌面上添加完Widget後,若是長按你會發如今Widget四個邊緣會出現拖動框,若是拖動能夠調節小插件的大小,那麼這個拖動框在哪裏添加的呢,咱們看一下,其實這個方法是DragLayer中的addResizeFrame方法,這個方法是在Workspace中的onDrop方法中調用的,也就是放到桌面上的時候就添加了。

咱們看一下這個方法:

public void addResizeFrame(ItemInfo itemInfo, LauncherAppWidgetHostView widget,
            CellLayout cellLayout) {
        AppWidgetResizeFrame resizeFrame = new AppWidgetResizeFrame(getContext(),
                widget, cellLayout, this);

        LayoutParams lp = new LayoutParams(-1, -1);
        lp.customPosition = true;

        addView(resizeFrame, lp);
        mResizeFrames.add(resizeFrame);

        resizeFrame.snapToWidget(false);
    }複製代碼

首先建立AppWidgetResizeFrame對象,傳入參數LauncherAppWidgetHostView、CellLayout,還有draglayer:

public AppWidgetResizeFrame(Context context,
            LauncherAppWidgetHostView widgetView, CellLayout cellLayout, DragLayer dragLayer) {

        //初始化數據
        ...

        // 初始化左側拖動點
        mLeftHandle = new ImageView(context);
        mLeftHandle.setImageResource(R.drawable.ic_widget_resize_handle);
        lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
                Gravity.LEFT | Gravity.CENTER_VERTICAL);
        lp.leftMargin = handleMargin;
        addView(mLeftHandle, lp);

        // 初始化右側拖動點
        // 初始化頂部拖動點
        // 初始化底部拖動點

        ...
    }複製代碼

拖動調整大小是在DragLayer中的onTouchEvent方法中:

@Override
    public boolean onTouchEvent(MotionEvent ev) {

        ...

        if (mCurrentResizeFrame != null) {
            handled = true;
            switch (action) {
                case MotionEvent.ACTION_MOVE:
                    mCurrentResizeFrame.visualizeResizeForDelta(x - mXDown, y - mYDown);
                    break;
                case MotionEvent.ACTION_CANCEL:
                case MotionEvent.ACTION_UP:
                    mCurrentResizeFrame.visualizeResizeForDelta(x - mXDown, y - mYDown);
                    mCurrentResizeFrame.onTouchUp();
                    mCurrentResizeFrame = null;
            }
        }
        if (handled) return true;
        return mDragController.onTouchEvent(ev);
    }複製代碼

由上面代碼能夠看出拖拽的的時候調用visualizeResizeForDelta方法,手指擡起的時候調用visualizeResizeForDelta方法和onTouchUp方法,咱們先看visualizeResizeForDelta方法:

private void visualizeResizeForDelta(int deltaX, int deltaY, boolean onDismiss) {
        updateDeltas(deltaX, deltaY);
        DragLayer.LayoutParams lp = (DragLayer.LayoutParams) getLayoutParams();

        if (mLeftBorderActive) {
            lp.x = mBaselineX + mDeltaX;
            lp.width = mBaselineWidth - mDeltaX;
        } else if (mRightBorderActive) {
            lp.width = mBaselineWidth + mDeltaX;
        }

        if (mTopBorderActive) {
            lp.y = mBaselineY + mDeltaY;
            lp.height = mBaselineHeight - mDeltaY;
        } else if (mBottomBorderActive) {
            lp.height = mBaselineHeight + mDeltaY;
        }

        resizeWidgetIfNeeded(onDismiss);
        requestLayout();
    }複製代碼

首先調用updateDeltas方法:

public void updateDeltas(int deltaX, int deltaY) {
        if (mLeftBorderActive) {
            mDeltaX = Math.max(-mBaselineX, deltaX); 
            mDeltaX = Math.min(mBaselineWidth - 2 * mTouchTargetWidth, mDeltaX);
        } else if (mRightBorderActive) {
            mDeltaX = Math.min(mDragLayer.getWidth() - (mBaselineX + mBaselineWidth), deltaX);
            mDeltaX = Math.max(-mBaselineWidth + 2 * mTouchTargetWidth, mDeltaX);
        }

        if (mTopBorderActive) {
            mDeltaY = Math.max(-mBaselineY, deltaY);
            mDeltaY = Math.min(mBaselineHeight - 2 * mTouchTargetWidth, mDeltaY);
        } else if (mBottomBorderActive) {
            mDeltaY = Math.min(mDragLayer.getHeight() - (mBaselineY + mBaselineHeight), deltaY);
            mDeltaY = Math.max(-mBaselineHeight + 2 * mTouchTargetWidth, mDeltaY);
        }
    }複製代碼

主要是根據上下左右點來計算mDeltaX和mDeltaY的值,而後設定DragLayer.LayoutParams的值,而後調用resizeWidgetIfNeeded方法:

private void resizeWidgetIfNeeded(boolean onDismiss) {
        ...

        if (mLeftBorderActive) {
            cellXInc = Math.max(-cellX, hSpanInc);
            cellXInc = Math.min(lp.cellHSpan - mMinHSpan, cellXInc);
            hSpanInc *= -1;
            hSpanInc = Math.min(cellX, hSpanInc);
            hSpanInc = Math.max(-(lp.cellHSpan - mMinHSpan), hSpanInc);
            hSpanDelta = -hSpanInc;

        }

        ...

        // Update the widget's dimensions and position according to the deltas computed above
        if (mLeftBorderActive || mRightBorderActive) {
            spanX += hSpanInc;
            cellX += cellXInc;
            if (hSpanDelta != 0) {
                mDirectionVector[0] = mLeftBorderActive ? -1 : 1;
            }
        }

        ...

        if (mCellLayout.createAreaForResize(cellX, cellY, spanX, spanY, mWidgetView,
                mDirectionVector, onDismiss)) {
            lp.tmpCellX = cellX;
            lp.tmpCellY = cellY;
            lp.cellHSpan = spanX;
            lp.cellVSpan = spanY;
            mRunningVInc += vSpanDelta;
            mRunningHInc += hSpanDelta;
            if (!onDismiss) {
                updateWidgetSizeRanges(mWidgetView, mLauncher, spanX, spanY);
            }
        }
        mWidgetView.requestLayout();
    }複製代碼

這裏計算拖拽過程當中的參數,而後調用updateWidgetSizeRanges方法:

static void updateWidgetSizeRanges(AppWidgetHostView widgetView, Launcher launcher,
            int spanX, int spanY) {
        getWidgetSizeRanges(launcher, spanX, spanY, sTmpRect);
        widgetView.updateAppWidgetSize(null, sTmpRect.left, sTmpRect.top,
                sTmpRect.right, sTmpRect.bottom);
    }複製代碼

首先調用getWidgetSizeRanges方法來設定sTmpRect參數,而後調用widgetView.updateAppWidgetSize方法更新widget大小,而後調用mWidgetView.requestLayout方法刷新widget。

咱們再看onTouchUp方法:

public void onTouchUp() {
        int xThreshold = mCellLayout.getCellWidth() + mCellLayout.getWidthGap();
        int yThreshold = mCellLayout.getCellHeight() + mCellLayout.getHeightGap();

        ...

        post(new Runnable() {
            @Override
            public void run() {
                snapToWidget(true);
            }
        });
    }複製代碼

這個方法是調整完widget大小手指離開屏幕時調用的,主要調用了snapToWidget方法,這個方法代碼就不貼了,主要是四個點的動畫,代碼很簡單。

到此widget的加載、添加以及大小調整就介紹完了,整個過程也是比較複雜的,因此仍是要好好熟悉一下。

最後

同步發佈:www.codemx.cn/2016/12/18/…

Github地址:github.com/yuchuangu85…

微信公衆帳號:Code-MX

注:本文原創,轉載請註明出處,多謝。

相關文章
相關標籤/搜索