歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android將Widget添加到自己的應用程序

Android將Widget添加到自己的應用程序

日期:2017/3/1 11:10:46   编辑:Linux編程

Widget添加方法:長安桌面-彈出Widget列表-選擇之即添加到桌面,下面就實現了一個支持添加到自己應用程序的功能,廢話不多說,直接上代碼。

請看效果圖:

1、通過繼承ViewGroup來實現一個能添加Widget的控件

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