直接上代码
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"