1,在baseactivity中寫邏輯代碼java
//添加懸浮窗口 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,佈局文件android
<?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>