Android开发---制作桌面可移动控件
Android开发---制作桌面可移动控件
做Android的应该经常会看见桌面上显示歌词,或者流量监控的悬浮窗。今天通过一个简单的实例来学习。
先看看效果。
1. 先建一个top_window.xml。这个就是用来在桌面上显示的控件。
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:background="#ffffff"
- android:orientation="vertical" >
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="点我就能移动~"
- android:textColor="#000000" />
- </LinearLayout>
2. 建一个类继承自Application
- /*
- * 主要用到两个类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);
- }
- }
其他的不用更改,直接运行即可看到效果。
源码下载:
免费下载地址在 http://linux.bkjia.com/
用户名与密码都是www.bkjia.com
具体下载目录在 /2012年资料/8月/19日/Android开发---制作桌面可移动控件
评论暂时关闭