android悬浮按钮实现方法
jopen
9年前
网上找了好多悬浮按钮的实现方法,但是好多都是通过service来实现的,特别不方便。现在直接写在baseactivity中。
1,在baseactivity中写逻辑代码
//添加悬浮窗口 WindowManager mWindowManager; WindowManager.LayoutParams wmParams; LinearLayout mFloatLayout; //悬浮图标 public ImageView mFloatView; /** * 屏幕的宽度和高度 */ protected int mScreenWidth; protected int mScreenHeight; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); //获取屏幕宽高 DisplayMetrics metric = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metric); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); mScreenWidth = metric.widthPixels; mScreenHeight = metric.heightPixels; //getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED, FLAG_HOMEKEY_DISPATCHED); }/** * 用法直接在需要使用的界面里引用该函数,然后给该函数添加监听事件 * createFloatView(Rcjc.this); * mFloatView.setOnClickListener; * */ //添加悬浮按钮 @SuppressWarnings("unused") public void createFloatView(Context cx) { //获取LayoutParams对象 wmParams = new WindowManager.LayoutParams(); //获取的是LocalWindowManager对象 mWindowManager = this.getWindowManager(); //mWindowManager = getWindow().getWindowManager(); //获取的是CompatModeWrapper对象 //mWindowManager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE); wmParams.type = LayoutParams.TYPE_PHONE; wmParams.format = PixelFormat.RGBA_8888;; wmParams.flags = LayoutParams.FLAG_NOT_FOCUSABLE; wmParams.gravity = Gravity.LEFT| Gravity.TOP; wmParams.x = mScreenWidth-50; wmParams.y = 70; wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT; wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT; LayoutInflater inflater = this.getLayoutInflater();//LayoutInflater.from(getApplication()); mFloatLayout = (LinearLayout) inflater.inflate(R.layout.floating, null); mWindowManager.addView(mFloatLayout, wmParams); //setContentView(R.layout.main); mFloatView = (ImageView)mFloatLayout.findViewById(R.id.floatButton); //绑定触摸移动监听 mFloatView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub wmParams.x = (int)event.getRawX() - mFloatLayout.getWidth()/2; //25为状态栏高度 wmParams.y = (int)event.getRawY() - mFloatLayout.getHeight()/2 - 40; mWindowManager.updateViewLayout(mFloatLayout, wmParams); return false; } });
2,布局文件
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ImageView android:id="@+id/floatButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/floatbtn" /> </LinearLayout>