上一章墨香帶你學Launcher之(六)--拖拽我們介紹了Launcher的拖拽過程,涉及到的範圍比較廣,包括圖示的拖拽,桌面上CellLayout的拖拽,小部件的拖拽,以及跨不同部件的拖拽,設計思想非常巧妙,不過整個流程相對也比較好掌握,只要跟著上一章的流程自己多跟蹤幾遍基本就熟悉了。按照計劃本章我們繼續學習Launcher的Widget的載入、新增以及Widget的大小調節。
Widget的資料載入
其實我們在第二章墨香帶你學Launcher之(二)-資料載入流程介紹過Widget資料的載入,相對只是簡單的做了介紹,下面我們稍微講的詳細點。
我們知道Widget的資料載入開始在LauncherModel中的updateWidgetsModel方法中,我們看下程式碼:
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的,程式碼:
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的是相容元件,我們看看是怎麼相容的,
我們下面程式碼:
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,這兩個有什麼不同,我們下面分析。
下面我們看如何獲取Widget列表物件:
List<AppWidgetProviderInfo> widgets = wm.getAllProviders();複製程式碼
getAllProviders()方法是一個抽象方法,所以我們看哪裡進行了複寫,
可以看到還是上面兩個相容類複寫了該方法,我們看這個兩個類中做了什麼處理,先看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
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
注:本文原創,轉載請註明出處,多謝。