我有这个使用服务激活的覆盖按钮。所以它是一个背景按钮。即使其他程序正在运行,您也可以看到该按钮。但是,我在按钮上添加一个功能时遇到问题,当我按住它时,我可以将它拖到任何我想要的屏幕上。我在这里检查了一些拖放选项,但我无法在我的程序中正确应用它。
在我的dragDrop()
方法中,由于以下转换错误,它不起作用:
error(WindowManagerLayoutParams could not be cast on Freamelayout.LayoutParams)..
这是我的服务代码:
public class MainPowerAndVolumeService extends Service {
private ViewGroup mView;
private LayoutInflater inflater;
private ImageButton mainButton;
private Button testButton;
@Override
public IBinder
onBind(Intent intent) {
return null;
}
public void onCreate( ) {
super.onCreate();
/*This will make your window or layout to be overlay and of course you can click the buttons*/
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT
);
/*This will load the main.xml view through inflate*/
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mView = (ViewGroup) inflater.inflate(R.layout.main, null);
mainButton =(ImageButton) mView.findViewById(R.id.MainButton);
wm.addView(mView,params);
buttonListener();
dragDrop( );
}
public void dragDrop(){
mainButton.setOnTouchListener(new View.OnTouchListener() {
int prevX,prevY;
/**this does not work since framelayout could not be cast to the Window Manager**/
@Override
public boolean onTouch(final View v, final MotionEvent event) {
final FrameLayout.LayoutParams par = (FrameLayout.LayoutParams) v.getLayoutParams();
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE: {
par.topMargin += (int) event.getRawY() - prevY;
prevY = (int) event.getRawY();
par.leftMargin += (int) event.getRawX() - prevX;
prevX = (int) event.getRawX();
v.setLayoutParams(par);
return true;
}
case MotionEvent.ACTION_UP: {
par.topMargin += (int) event.getRawY() - prevY;
par.leftMargin += (int) event.getRawX() - prevX;
v.setLayoutParams(par);
return true;
}
case MotionEvent.ACTION_DOWN: {
prevX = (int) event.getRawX();
prevY = (int) event.getRawY();
par.bottomMargin = -2 * v.getHeight();
par.rightMargin = -2 * v.getWidth();
v.setLayoutParams(par);
return true;
}
}
return false;
}
});
}
public void buttonListener(){
mainButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Intent intent = Intent.
Toast.makeText(MainPowerAndVolumeService.this,
"ImageButton (selector) is clicked!",
Toast.LENGTH_SHORT).show();
}
});
}
public void onDestroy(){
super.onDestroy();
((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(mView);
}
}