歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android開發---制作桌面可移動控件

Android開發---制作桌面可移動控件

日期:2017/3/1 10:12:09   编辑:Linux編程

做Android的應該經常會看見桌面上顯示歌詞,或者流量監控的懸浮窗。今天通過一個簡單的實例來學習。

先看看效果。

1. 先建一個top_window.xml。這個就是用來在桌面上顯示的控件。

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="wrap_content"
  4. android:layout_height="wrap_content"
  5. android:background="#ffffff"
  6. android:orientation="vertical" >
  7. <TextView
  8. android:layout_width="wrap_content"
  9. android:layout_height="wrap_content"
  10. android:text="點我就能移動~"
  11. android:textColor="#000000" />
  12. </LinearLayout>

2. 建一個類繼承自Application

  1. /*
  2. * 主要用到兩個類WindowManager, WindowManager.LayoutParams. 對窗口進行管理.
  3. */
  4. package com.orgcent.desktop;
  5. import android.app.Application;
  6. import android.content.Context;
  7. import android.view.LayoutInflater;
  8. import android.view.MotionEvent;
  9. import android.view.View;
  10. import android.view.WindowManager;
  11. import android.view.View.OnTouchListener;
  12. public class BaseAppliction extends Application
  13. {
  14. WindowManager mWM;
  15. WindowManager.LayoutParams mWMParams;
  16. @Override
  17. public void onCreate()
  18. {
  19. mWM = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
  20. final View win = LayoutInflater.from(this).inflate(
  21. R.layout.top_window, null);
  22. win.setOnTouchListener(new OnTouchListener()
  23. {
  24. float lastX, lastY;
  25. public boolean onTouch(View v, MotionEvent event)
  26. {
  27. final int action = event.getAction();
  28. float x = event.getX();
  29. float y = event.getY();
  30. if (action == MotionEvent.ACTION_DOWN)
  31. {
  32. lastX = x;
  33. lastY = y;
  34. } else if (action == MotionEvent.ACTION_MOVE)
  35. {
  36. mWMParams.x += (int) (x - lastX);
  37. mWMParams.y += (int) (y - lastY);
  38. mWM.updateViewLayout(win, mWMParams);
  39. }
  40. return true;
  41. }
  42. });
  43. WindowManager wm = mWM;
  44. WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams();
  45. mWMParams = wmParams;
  46. wmParams.type = 2002; //type是關鍵,這裡的2002表示系統級窗口,你也可以試試2003。可取查幫助文檔
  47. wmParams.format = 1;
  48. wmParams.flags = 40;
  49. wmParams.width = 100;//設定大小
  50. wmParams.height = 30;
  51. wm.addView(win, wmParams);
  52. }
  53. }

其他的不用更改,直接運行即可看到效果。

源碼下載:

免費下載地址在 http://linux.linuxidc.com/

用戶名與密碼都是www.linuxidc.com

具體下載目錄在 /2012年資料/8月/19日/Android開發---制作桌面可移動控件

Copyright © Linux教程網 All Rights Reserved