Android开发---制作桌面可移动控件
做android的应该经常会看见桌面上显示歌词,或者流量监控的悬浮窗。今天通过一个简单的实例来学习。先看看效果。
1. 先建一个top_window.xml。这个就是用来在桌面上显示的控件。
/** 主要用到两个类WindowManager, WindowManager.LayoutParams. 对窗口进行管理.*/package com.orgcent.desktop;import android.app.Application;import android.content.Context;import android.view.LayoutInflater;import android.view.MotionEvent;import android.view.View;import android.view.WindowManager;import android.view.View.OnTouchListener;public class BaseAppliction extends Application{ WindowManager mWM; WindowManager.LayoutParams mWMParams; @Override public void onCreate() { mWM = (WindowManager) getSystemService(Context.WINDOW_SERVICE); final View win = LayoutInflater.from(this).inflate( R.layout.top_window, null); win.setOnTouchListener(new OnTouchListener() { float lastX, lastY; public boolean onTouch(View v, MotionEvent event) { final int action = event.getAction(); float x = event.getX(); float y = event.getY(); if (action == MotionEvent.ACTION_DOWN) { lastX = x; lastY = y; } else if (action == MotionEvent.ACTION_MOVE) { mWMParams.x += (int) (x - lastX); mWMParams.y += (int) (y - lastY); mWM.updateViewLayout(win, mWMParams); } return true; } }); WindowManager wm = mWM; WindowManager.LayoutParams wmParams = new WindowManager.LayoutParams(); mWMParams = wmParams; wmParams.type = 2002; //type是关键,这里的2002表示系统级窗口,你也可以试试2003。可取查帮助文档 wmParams.format = 1; wmParams.flags = 40; wmParams.width = 100;//设定大小 wmParams.height = 30; wm.addView(win, wmParams); }}