WindowManager之实现类似360桌面悬浮物

直接上代码

 

public class WindowMangerTestActivityaa extends Activity {
 float rawX;
 float rawY;
 float xx = 0.0f;
 float yy = 0.0f;
 WindowManager manager;
 WindowManager.LayoutParams params;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  // setContentView(R.layout.main);
  final TextView tv = new TextView(this);
  manager = (WindowManager) getApplicationContext().getSystemService(
    Context.WINDOW_SERVICE);
  params = new WindowManager.LayoutParams();
  params.x = 0;
  params.y = 0;
  tv.setBackgroundColor(Color.WHITE);
  tv.setTextColor(Color.BLACK);
  tv.setText("adfasdfsdf");
  params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
  params.alpha = 0.5f;
  params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT
    | WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY;
  params.format = 1;
  params.gravity = Gravity.LEFT| Gravity.TOP;
  params.height = 80;
  params.width = 80;
  manager.addView(tv, params);
  tv.setOnTouchListener(new OnTouchListener() {
   @Override
   public boolean onTouch(View v, MotionEvent event) {
    rawX = event.getRawX();
    rawY = event.getRawY();
    int action = event.getAction();
    switch (action) {
    case MotionEvent.ACTION_DOWN:
     xx = event.getX();
     yy = event.getY();
     break;

    case MotionEvent.ACTION_MOVE:
     params.x = (int) (rawX - xx);
     params.y = (int) (rawY - yy);
     manager.updateViewLayout(tv, params);
     break;

    default:
     break;
    }
    // TODO Auto-generated method stub
    return true;
   }
  });
 }

}

请注意

1.getSystemService之前的那个getApplicationContext是必须的,一般情况下,大家可能会运用this(我也是),用了this之后导致,textview只能在当前的activity上显示,返回之后textview消失

2.params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
    | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;否则textview是拖不动的。

3.在AndroidManifest.xml中添加权限<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

4.在AndroidManifest.xml中的Activity节点属性中添加android:theme="@android:style/Theme.NoDisplay"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值