Android将Widget添加到自己的应用程序


Widget添加方法:长安桌面-弹出Widget列表-选择之即添加到桌面,下面就实现了一个支持添加到自己应用程序的功能,废话不多说,直接上代码。

请看效果图:

1、通过继承ViewGroup来实现一个能添加Widget的控件

  1. package cn.winplus.w2h;  
  2.   
  3. import Android.content.Context;  
  4. import android.view.MotionEvent;  
  5. import android.view.View;  
  6. import android.view.ViewGroup;  
  7.   
  8. public class WidgetLayout extends ViewGroup {  
  9.   
  10.     // 存放touch的坐标   
  11.     private int[] cellInfo = new int[2];  
  12.     private OnLongClickListener mClickListener;  
  13.   
  14.     public WidgetLayout(Context context) {  
  15.         super(context);  
  16.   
  17.         mClickListener = new OnLongClickListener() {  
  18.   
  19.             @Override  
  20.             public boolean onLongClick(View arg0) {  
  21.   
  22.                 return false;  
  23.             }  
  24.         };  
  25.   
  26.     }  
  27.   
  28.     public void addInScreen(View child, int width, int height) {  
  29.         LayoutParams lp = new LayoutParams(width, height);  
  30.         lp.x = cellInfo[0];  
  31.         lp.y = cellInfo[1];  
  32.         child.setOnLongClickListener(mClickListener);  
  33.         addView(child, lp);  
  34.     }  
  35.   
  36.     @Override  
  37.     protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {  
  38.         LayoutParams lParams;  
  39.         for (int i = 0; i < getChildCount(); i++) {  
  40.             lParams = (LayoutParams) getChildAt(i).getLayoutParams();  
  41.             getChildAt(i).layout(lParams.x, lParams.y,  
  42.                     lParams.x + lParams.width, lParams.y + lParams.height);  
  43.         }  
  44.     }  
  45.   
  46.     @Override  
  47.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  48.         super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
  49.   
  50.         LayoutParams lParams;  
  51.         for (int i = 0; i < getChildCount(); i++) {  
  52.             lParams = (LayoutParams) getChildAt(i).getLayoutParams();  
  53.             getChildAt(i).measure(  
  54.                     MeasureSpec.makeMeasureSpec(MeasureSpec.EXACTLY,lParams.width),  
  55.                     MeasureSpec.makeMeasureSpec(MeasureSpec.EXACTLY,lParams.height));  
  56.         }  
  57.     }  
  58.   
  59.     @Override  
  60.     public boolean dispatchTouchEvent(MotionEvent ev) {  
  61.         cellInfo[0] = (int) ev.getX();  
  62.         cellInfo[1] = (int) ev.getY();  
  63.         return super.dispatchTouchEvent(ev);  
  64.     }  
  65.   
  66.     private class LayoutParams extends ViewGroup.LayoutParams {  
  67.   
  68.         int x;  
  69.         int y;  
  70.   
  71.         public LayoutParams(int arg0, int arg1) {  
  72.             super(arg0, arg1);  
  73.         }  
  74.   
  75.     }  
  76.   
  77. }
  • 1
  • 2
  • 下一页

相关内容