Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android懸浮窗口

Android懸浮窗口

編輯:關於Android編程

FloatService:

package com.home.floatwindow;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.home.testfolatwindow.R;

public class FloatService extends Service {

	private WindowManager wm;
	private WindowManager.LayoutParams wmlp;
	private LinearLayout layout;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		createFloatView();
	}

	private void createFloatView() {
		wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
		wmlp = new WindowManager.LayoutParams();
		wmlp.type = LayoutParams.TYPE_PHONE;
		// 設置圖片格式,效果為背景透明
		wmlp.format = PixelFormat.RGBA_8888;
		// 設置浮動窗口不可聚焦
		wmlp.flags = LayoutParams.FLAG_NOT_FOCUSABLE;
		wmlp.gravity = Gravity.LEFT | Gravity.TOP;
		wmlp.x = 0;
		wmlp.y = 0;
		wmlp.width = WindowManager.LayoutParams.WRAP_CONTENT;
		wmlp.height = WindowManager.LayoutParams.WRAP_CONTENT;
		layout = getLayout();
		wm.addView(layout, wmlp);
		layout.measure(View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
				.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
		ImageView iv = (ImageView) layout.findViewById(1);
		iv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.i("onClick", "onClick");
			}
		});
		iv.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// getRawX是觸摸位置相對於屏幕的坐標,getX是相對於按鈕的坐標
				wmlp.x = (int) event.getRawX() - layout.getMeasuredWidth() / 2;
				// 減25為狀態欄的高度
				wmlp.y = (int) event.getRawY() - layout.getMeasuredHeight() / 2
						- 25;
				wm.updateViewLayout(layout, wmlp);
				return false;
			}
		});
	}

	private LinearLayout getLayout() {
		LinearLayout layout = new LinearLayout(this);
		ImageView iv = new ImageView(this);
		iv.setBackgroundResource((R.drawable.ic_launcher));
		iv.setId(1);
		layout.addView(iv);
		return layout;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (layout != null) {
			// 移除懸浮窗口
			wm.removeView(layout);
		}
	}
}


權限:


  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved