馬上加入Android 台灣中文網,立即免費下載應用遊戲。
您需要 登錄 才可以下載或查看,沒有帳號?註冊
x
如果想讓你的應用支持appwidget,需要注意的幾點:
1.必須調用AppWidgetHost的startListening方法來監聽appwidget的狀態變化,否則添加上去的appwidget不會更新的。
2.需要override一個onActivityResult方法,來接收添加appwidget和appwidget的配置activity的返回值。
3.啟動AppWidgetManager.ACTION_APPWIDGET_PICK這個Intent,必須要給列表中加上自己定義的一個選項,否則出錯。如本例中是用的Search。
下面是完整的教程:
首先是得定義一個承載appwidget的容器,系統的Launcher裡面 是用的CellLayout,實現的很不錯。我這裡就用一個簡單的自定義ViewGroup來搞定,它是以長按的坐標處為要添加的appwidget的起 始位置,簡單點說就是按到哪兒就添加到哪兒。- package chroya.demo.widget;
-
- import android.content.Context;
- import android.view.MotionEvent;
- import android.view.View;
- import android.view.ViewGroup;
-
- /**
- * 承載widget的容器
- * @author chroya
- */
- public class WidgetLayout extends ViewGroup {
- //存放touch的坐標
- private int[] cellInfo = new int[2];
- private OnLongClickListener mLongClickListener;
-
- public WidgetLayout(Context context) {
- super(context);
- mLongClickListener = new OnLongClickListener() {
-
- @Override
- public boolean onLongClick(View v) {
-
- return false;
- }
- };
- }
-
- public void addInScreen(View child, int width, int height) {
- LayoutParams lp = new LayoutParams(width, height);
- lp.x = cellInfo[0];
- lp.y = cellInfo[1];
- child.setOnLongClickListener(mLongClickListener);
- addView(child, lp);
- }
-
- @Override
- protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
- super.onMeasure(widthMeasureSpec, heightMeasureSpec);
- LayoutParams lp;
- for(int index=0; index<getChildCount(); index++) {
- lp = (LayoutParams) getChildAt(index).getLayoutParams();
- getChildAt(index).measure(
- MeasureSpec.makeMeasureSpec(MeasureSpec.EXACTLY, lp.width),
- MeasureSpec.makeMeasureSpec(MeasureSpec.EXACTLY, lp.height));
- }
- }
-
- @Override
- public boolean dispatchTouchEvent(MotionEvent event) {
- cellInfo[0] = (int)event.getX();
- cellInfo[1] = (int)event.getY();
- return super.dispatchTouchEvent(event);
- }
-
- @Override
- protected void onLayout(boolean changed, int l, int t, int r, int b) {
- LayoutParams lp;
- for(int index=0; index<getChildCount(); index++) {
- lp = (LayoutParams) getChildAt(index).getLayoutParams();
- getChildAt(index).layout(lp.x, lp.y, lp.x+lp.width, lp.y+lp.height);
- }
- }
-
- public static class LayoutParams extends ViewGroup.LayoutParams {
- int x;
- int y;
-
- public LayoutParams(int width, int height) {
- super(width, height);
- }
- }
- }
複製代碼 然後是重點了。還記得系統默認的桌面上,長按的時候出現的上下文菜單嗎?裡面 有好幾個選項,選擇widget之後,會彈出一個已經安裝的widget列表,選擇一個widget之後,就會添加到桌面。我們可以把第一步去掉,長按之 後,直接彈出已安裝的widget列表,這是一個activity,用AppWidgetManager.ACTION_APPWIDGET_PICK這 個Intent來啟動,必須帶上Extras,下面給出代碼中有,不詳敘。運行效果如下:
|