help悬浮按钮

效果:随手指拖动,松开停留在原地;点击弹到左下角,并向上动画发出多个按钮;再次点击动画收回按钮,并弹回点击前的位置

@drawable/oval_004b7c_full
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#004b7c"/>
</shape>
oval_004b7c
<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="oval"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#fff"/>
    <stroke android:color="#004b7c" android:width="1dp"/>
</shape>

 

<?xml version="1.0" encoding="UTF-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/big4_window_layout"
	android:layout_width="wrap_content"
	android:layout_height="match_parent"
	android:layout_gravity="bottom|right"
	android:layout_marginBottom="100dp">

	<TextView
		android:id="@+id/help1"
		android:layout_width="50dp"
		android:layout_height="50dp"
		android:gravity="center"
		android:textColor="#fff"
		android:text="客服1"
		android:textSize="15sp"
		android:background="@drawable/oval_004b7c_full"
		android:layout_gravity="bottom"/>

	<TextView
		android:id="@+id/help2"
		android:layout_width="50dp"
		android:layout_height="50dp"
		android:gravity="center"
		android:textColor="#fff"
		android:text="客服2"
		android:textSize="15sp"
		android:background="@drawable/oval_004b7c_full"
		android:layout_gravity="bottom" />

	<TextView
		android:id="@+id/help3"
		android:layout_width="50dp"
		android:layout_height="50dp"
		android:gravity="center"
		android:textColor="#fff"
		android:text="客服3"
		android:textSize="15sp"
		android:background="@drawable/oval_004b7c_full"
		android:layout_gravity="bottom"/>
	<TextView
		android:id="@+id/help4"
		android:layout_width="50dp"
		android:layout_height="50dp"
		android:gravity="center"
		android:textColor="#fff"
		android:text="客服4"
		android:textSize="15sp"
		android:background="@drawable/oval_004b7c_full"
		android:layout_gravity="bottom"/>
	<TextView
		android:id="@+id/percent1"
		android:layout_width="50dp"
		android:layout_height="50dp"
		android:gravity="center"
		android:textColor="#004b7c"
		android:text="help"
		android:textSize="15sp"
		android:background="@drawable/oval_004b7c"
		android:layout_gravity="bottom"/>
</FrameLayout>
FloatWindowBigView.java
package com.welldone.home.view.floatbutton4;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.welldone.home.R;

import java.util.ArrayList;
import java.util.List;

public class FloatWindowBigView extends LinearLayout implements View.OnClickListener {

	private int[] res = {R.id.percent1, R.id.help1, R.id.help2, R.id.help3, R.id.help4};
	private List<TextView> list_img = new ArrayList<TextView>();
	public static int viewHeight;
	public static int viewWidth;

	/**
	 * true:点击按钮时,弹出菜单
	 * false:点击按钮时,关闭菜单
	 */
	private boolean flag = true;

	public FloatWindowBigView(final Context context) {
		super(context);
		//用于做为大悬浮窗的布局
		LayoutInflater.from(context).inflate(R.layout.float4_window_big, this);
		FrameLayout view = (FrameLayout) findViewById(R.id.big4_window_layout);
		viewHeight = view.getLayoutParams().height;
		viewWidth = view.getLayoutParams().width;

		for(int i = 0; i < res.length; i ++) {
			TextView tv_help = (TextView) findViewById(res[i]);
			list_img.add(tv_help);
			tv_help.setOnClickListener(this);
		}

		if(flag) {
			startAnim();
		}else {
			closeAnim();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.percent1:
				if(flag) {
					startAnim();
				}else {
					closeAnim();
				}
				break;
			case R.id.help1:
			case R.id.help2:
			case R.id.help3:
			case R.id.help4:
                closeAnim();
				break;
		}
	}

	/**
	 * 弹出按钮的动画
	 */
	private void startAnim() {
		for(int i = 1; i < res.length ; i ++) {
			ObjectAnimator animator = ObjectAnimator.ofFloat(list_img.get(i),"translationY",0f,-(res.length-i)*130f);
//            ObjectAnimator animator1 = ObjectAnimator.ofFloat(list_img.get(i),"translationX", 0f , (i-1)*50f);
			AnimatorSet animSet = new AnimatorSet();
			animSet.play(animator);
			animSet.setStartDelay(300);
			animSet.start();
			flag = false;
		}
	}

	/**
	 * 收回弹出按钮的动画
	 */
	private void closeAnim() {
		for(int i = 1; i < res.length; i ++) {
			//给出一个沿Y轴移动的动画
			ObjectAnimator animator = ObjectAnimator.ofFloat(list_img.get(i),"translationY",-(res.length-i)*130f,0f );
			//给出一个沿X轴移动的动画
//            ObjectAnimator animator1 = ObjectAnimator.ofFloat(list_img.get(i),"translationX",(i-1)*50f,0f );
			//定义属性动画集合的对象
			AnimatorSet animSet = new AnimatorSet();
			//通过with方法,让两个动画同时进行
			animSet.play(animator);
			//设置延迟时间,让菜单内容相继弹出
			animSet.setStartDelay(300);
			animSet.start();
			//然后,设置flag为true,当再次点击的时候,收回菜单
			flag = true;
            // 点击返回的时候,移除大悬浮窗,创建小悬浮窗
            MyWindowManager.removeBigWindow(getContext());
            MyWindowManager.createSmallWindow(getContext());
		}
	}
}
package com.welldone.home.view.floatbutton4;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;


//Service的生命周期:http://www.cnblogs.com/mengdd/archive/2013/03/24/2979944.html
public class FloatWindowService extends Service {

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

    //Service一开启就开始记时刷新
//设置多久刷新一次数据
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        MyWindowManager.createSmallWindow(getApplicationContext());
        return super.onStartCommand(intent, flags, startId);
    }

}
package com.welldone.home.view.floatbutton4;

import android.content.Context;
import android.graphics.PixelFormat;
import android.view.Gravity;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;

/**
 * 这个类负责了控制大悬浮窗,小悬浮窗的创建和移除,系统内存使用百分比的计算等操作。
 * 
 * 
 * 主要是通过WindowManager这个类来实现的,调用这个类的addView方法用于添加一个悬浮窗,updateViewLayout方法用于更新悬浮窗的参数,removeView用于移除悬浮窗。
 * WindowManager.LayoutParams用于提供悬浮窗所需的参数,里面的几个变量:
 * 其余参数详解:http://blog.csdn.net/xyz_fly/article/details/7546210
 *   type:用于确定悬浮窗的类型,一般设为2002,表示在所有应用程序之上,但在状态栏之下。
 *   flags:用于确定悬浮窗的行为,比如说不可聚焦,非模态对话框等等,属性非常多,大家可以查看文档。
 *   gravity:用于确定悬浮窗的对齐方式,一般设为左上角对齐,这样当拖动悬浮窗的时候方便计算坐标。
 *   x:用于确定悬浮窗的位置,如果要横向移动悬浮窗,就需要改变这个值。
 *   y:用于确定悬浮窗的位置,如果要纵向移动悬浮窗,就需要改变这个值。
 *   width:用于指定悬浮窗的宽度。
 *   height:用于指定悬浮窗的高度。
 */
public class MyWindowManager {

	/**
	 * 小悬浮窗View的实例
	 */
	public static Floatbutton4 smallWindow;

	/**
	 * 大悬浮窗View的实例
	 */
	public static FloatWindowBigView bigWindow;

	/**
	 * 小悬浮窗View的参数
	 */
	private static LayoutParams smallWindowParams;

	/**
	 * 大悬浮窗View的参数
	 */
	private static LayoutParams bigWindowParams;

	/**
	 * 用于控制在屏幕上添加或移除悬浮窗
	 */
	private static WindowManager mWindowManager;

	/**
	 * 用于获取手机可用内存
	 */
//	private static ActivityManager mActivityManager;

	/**
	 * 创建一个小悬浮窗。初始位置为屏幕的右部中间位置。
	 *
	 * @param context
	 *            必须为应用程序的Context.
	 */
	public static void createSmallWindow(Context context) {
		WindowManager windowManager = getWindowManager(context);
		//获得手机屏幕的高宽
		int screenWidth = windowManager.getDefaultDisplay().getWidth();
		int screenHeight = windowManager.getDefaultDisplay().getHeight();
		if (smallWindow == null) {
			smallWindow = new Floatbutton4(context);
			//小悬浮窗View的参数
			if (smallWindowParams == null) {
				smallWindowParams = new LayoutParams();
				//用于确定悬浮窗的类型:在所有应用程序之上,但在状态栏之下
				smallWindowParams.type = LayoutParams.TYPE_PHONE;
				//期望的位图格式。默认为不透明
				smallWindowParams.format = PixelFormat.RGBA_8888;
				//用于确定悬浮窗的行为,比如说不可聚焦,非模态对话框等等
				smallWindowParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
						| LayoutParams.FLAG_NOT_FOCUSABLE;
				//用于确定悬浮窗的对齐方式,一般设为左上角对齐,这样当拖动悬浮窗的时候方便计算坐标。
				smallWindowParams.gravity = Gravity.LEFT | Gravity.TOP;
				//用于指定悬浮窗的宽度,高度。
				smallWindowParams.width = Floatbutton4.viewWidth;
				smallWindowParams.height = Floatbutton4.viewHeight;
				//用于确定悬浮窗的位置
				smallWindowParams.x = screenWidth;
				smallWindowParams.y = screenHeight / 2;
			}
			smallWindow.setParams(smallWindowParams);
			windowManager.addView(smallWindow, smallWindowParams);
		}
	}

	/**
	 * 将小悬浮窗从屏幕上移除。
	 *
	 * @param context
	 *            必须为应用程序的Context.
	 */
	public static void removeSmallWindow(Context context) {
		if (smallWindow != null) {
			WindowManager windowManager = getWindowManager(context);
			windowManager.removeView(smallWindow);
			smallWindow = null;
		}
	}

	/**
	 * 创建一个大悬浮窗。位置为屏幕正中间。
	 *
	 * @param context
	 *            必须为应用程序的Context.
	 */
	public static void createBigWindow(Context context) {
		WindowManager windowManager = getWindowManager(context);
		int screenWidth = windowManager.getDefaultDisplay().getWidth();
		int screenHeight = windowManager.getDefaultDisplay().getHeight();
		if (bigWindow == null) {
			bigWindow = new FloatWindowBigView(context);
			if (bigWindowParams == null) {
				bigWindowParams = new LayoutParams();
				bigWindowParams.x = screenWidth - FloatWindowBigView.viewWidth;
				bigWindowParams.y = screenHeight - FloatWindowBigView.viewHeight;
				bigWindowParams.type = LayoutParams.TYPE_PHONE;
				bigWindowParams.format = PixelFormat.RGBA_8888;
				bigWindowParams.gravity = Gravity.LEFT | Gravity.TOP;
				bigWindowParams.width = FloatWindowBigView.viewWidth;
				bigWindowParams.height = FloatWindowBigView.viewHeight;
			}
			windowManager.addView(bigWindow, bigWindowParams);
		}
	}

	/**
	 * 将大悬浮窗从屏幕上移除。
	 * 
	 * @param context
	 *            必须为应用程序的Context.
	 */
	public static void removeBigWindow(Context context) {
		if (bigWindow != null) {
			WindowManager windowManager = getWindowManager(context);
			windowManager.removeView(bigWindow);
			bigWindow = null;
		}
	}

	/**
	 * 更新小悬浮窗的TextView上的数据,显示内存使用的百分比。
	 * 
	 * @param context
	 *            可传入应用程序上下文。
	 */
	/*public static void updateUsedPercent(Context context) {
		if (smallWindow != null) {
			TextView percentView = (TextView) smallWindow.findViewById(R.id.percent);
			percentView.setText(getUsedPercentValue(context));
		}
	}*/

	/**
	 * 是否有悬浮窗(包括小悬浮窗和大悬浮窗)显示在屏幕上。
	 * 
	 * @return 有悬浮窗显示在桌面上返回true,没有的话返回false。
	 */
	public static boolean isWindowShowing() {
		return smallWindow != null || bigWindow != null;
	}

	/**
	 * 如果WindowManager还未创建,则创建一个新的WindowManager返回。否则返回当前已创建的WindowManager。
	 * 
	 * @param context
	 *            必须为应用程序的Context.
	 * @return WindowManager的实例,用于控制在屏幕上添加或移除悬浮窗。
	 */
	private static WindowManager getWindowManager(Context context) {
		if (mWindowManager == null) {
			mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		}
		return mWindowManager;
	}

	/**
	 * 如果ActivityManager还未创建,则创建一个新的ActivityManager返回。否则返回当前已创建的ActivityManager。
	 * 
	 * @param context
	 *            可传入应用程序上下文。
	 * @return ActivityManager的实例,用于获取手机可用内存。
	 */
	/*private static ActivityManager getActivityManager(Context context) {
		if (mActivityManager == null) {
			mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		}
		return mActivityManager;
	}*/

	/**
	 * 计算已使用内存的百分比,并返回。
	 * 
	 * @param context
	 *            可传入应用程序上下文。
	 * @return 已使用内存的百分比,以字符串形式返回。
	 */
	/*public static String getUsedPercentValue(Context context) {
		String dir = "/proc/meminfo";
		try {
			FileReader fr = new FileReader(dir);
			BufferedReader br = new BufferedReader(fr, 2048);
			String memoryLine = br.readLine();
			String subMemoryLine = memoryLine.substring(memoryLine.indexOf("MemTotal:"));
			br.close();
			//\\D+表示一个以上的非数字字符
			//subMemoryLine.replaceAll("\\D+", "")的意思是把返回的字符串里的”MemTotal:“替换成"",也即去掉,只剩下数字信息。
			long totalMemorySize = Integer.parseInt(subMemoryLine.replaceAll("\\D+", ""));
			long availableSize = getAvailableMemory(context) / 1024;
			int percent = (int) ((totalMemorySize - availableSize) / (float) totalMemorySize * 100);
			return percent + "%";
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "悬浮窗";
	}*/

	/**
	 * 获取当前可用内存,返回数据以字节为单位。
	 * 
	 * @param context
	 *            可传入应用程序上下文。
	 * @return 当前可用内存。
	 */
	/*private static long getAvailableMemory(Context context) {
		ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
		getActivityManager(context).getMemoryInfo(mi);
		return mi.availMem;
	}*/

}
<?xml version="1.0" encoding="UTF-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/small_window_layout"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:layout_gravity="bottom">

	<TextView
		android:id="@+id/percent"
		android:layout_width="50dp"
		android:layout_height="50dp"
		android:gravity="center"
		android:textColor="#004b7c"
		android:text="help"
		android:textSize="15sp"
		android:background="@drawable/oval_004b7c"
		android:layout_gravity="bottom"/>
</FrameLayout>
package com.welldone.home.view.floatbutton4;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.welldone.home.R;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class Floatbutton4 extends FrameLayout {

    /**
     * 记录小悬浮窗的宽高
     */
    public static int viewWidth;
    public static int viewHeight;

    /**
     * 记录系统状态栏的高度
     */
    private static int statusBarHeight;

    /**
     * 用于更新小悬浮窗的位置
     */
    private WindowManager windowManager;

    /**
     * 小悬浮窗的参数
     */
    private WindowManager.LayoutParams mParams;

    /**
     * 记录当前手指位置相对于屏幕的坐标
     */
    private float xInScreen;
    private float yInScreen;

    /**
     * 记录手指初始按下时在屏幕上的横纵坐标的值
     */
    private float xDownInScreen;
    private float yDownInScreen;

    /**
     * 记录手指按下时在小悬浮窗的View上的横纵坐标的值
     */
    private float xInView;
    private float yInView;

    // 小图标加弹出新图标的id集合,小图标的id放第一位
    private int[] res = {R.id.percent, R.id.help1, R.id.help2, R.id.help3, R.id.help4};
    //放小图标好弹出新图标的组件集合
    private List<TextView> list_img = new ArrayList<TextView>();

    /**
     * flag
     * true:点击按钮时,弹出菜单
     * false:点击按钮时,关闭菜单
     */
    private boolean flag = true;

    /**
     * 当前按钮是否可移动(true:可移动)
     */
    private boolean state = true;
    //小图标按钮
    TextView percentView;
    //小图标按钮及弹出按钮的整个外布局
    FrameLayout view;

    public Floatbutton4(Context context) {
        this(context, null);
    }

    public Floatbutton4(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public Floatbutton4(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }

    private void initView(Context context) {
        windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        LayoutInflater.from(context).inflate(R.layout.float4_window_small, this);
        view = (FrameLayout) findViewById(R.id.small_window_layout);
        //小悬浮窗的宽高
        viewHeight = view.getLayoutParams().height;
        viewWidth = view.getLayoutParams().width;
        // help按钮
        percentView = (TextView) findViewById(R.id.percent);

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // 手指按下相对于悬浮窗的横纵坐标
                xInView = event.getX();
                yInView = event.getY();
                // 手指初始按下位置相对于屏幕的坐标(去掉了状态栏高度)
                xDownInScreen = event.getRawX();
                yDownInScreen = event.getRawY() - getStatusBarHeight();
                // 当前手指相对于屏幕的坐标
                xInScreen = event.getRawX();
                yInScreen = event.getRawY() - getStatusBarHeight();
                break;
            case MotionEvent.ACTION_MOVE:
                xInScreen = event.getRawX();
                yInScreen = event.getRawY() - getStatusBarHeight();
                updateViewPosition();
                break;
            case MotionEvent.ACTION_UP:
                if (Math.abs(xDownInScreen - xInScreen) < 5 && Math.abs(yDownInScreen - yInScreen) < 5) {
//                    xInScreen = screenWidth - viewWidth;
//                    // 这个100 是展开视图中,组建布局距离底部的高度,为了同步大视图关闭后的help位置
//                    yInScreen = screenHeight - 245 - viewHeight - getStatusBarHeight();
//                    updateViewPosition();
                    openBigWindow();
                }
                break;
            default:
                break;
        }
        return true;
    }

    /**
     * 打开大悬浮窗,关闭小悬浮窗
     */
    private void openBigWindow() {
        MyWindowManager.createBigWindow(getContext());
        MyWindowManager.removeSmallWindow(getContext());
    }

    /**
     * 将小悬浮窗的参数传入,用于更新小悬浮窗的位置
     */
    public void setParams(WindowManager.LayoutParams params) {
        mParams = params;
    }

    /**
     * 用于获取状态栏的高度。
     *
     * @return 返回状态栏高度的像素值。
     */
    private int getStatusBarHeight() {
        if (statusBarHeight == 0) {
            try {
                Class<?> c = Class.forName("com.android.internal.R$dimen");
                Object o = c.newInstance();
                Field field = c.getField("status_bar_height");
                int x = (Integer) field.get(o);
                statusBarHeight = getResources().getDimensionPixelSize(x);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return statusBarHeight;
    }

    /**
     * 更新小悬浮窗在屏幕中的位置
     */
    private void updateViewPosition() {
        // 被点击组件在屏幕中的坐标
        mParams.x = (int) (xInScreen - xInView);
        mParams.y = (int) (yInScreen - yInView);
        windowManager.updateViewLayout(this, mParams);
    }
}
if(MyWindowManager.smallWindow == null&&MyWindowManager.bigWindow == null) {
    //打开悬浮窗的服务                        
    Intent intent = new Intent(HomeActivity.this, FloatWindowService.class);
    startService(intent);
}

别忘了注册服务 

<service android:name=".view.floatbutton4.FloatWindowService" />

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值