悬浮窗代码设置边距颜色
时间: 2023-12-18 08:06:03 浏览: 137
悬浮窗代码
以下是一个简单的悬浮窗代码示例,其中设置了边距和颜色:
```java
public class FloatingView extends Service {
private WindowManager mWindowManager;
private View mFloatingView;
@Override
public void onCreate() {
super.onCreate();
// 创建悬浮窗视图
mFloatingView = LayoutInflater.from(this).inflate(R.layout.layout_floating_view, null);
// 设置边距
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
layoutParams.gravity = Gravity.TOP | Gravity.START;
layoutParams.x = 0;
layoutParams.y = 100;
// 设置边框颜色
GradientDrawable shape = new GradientDrawable();
shape.setShape(GradientDrawable.RECTANGLE);
shape.setStroke(2, Color.RED);
mFloatingView.setBackground(shape);
// 添加悬浮窗视图到 WindowManager
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.addView(mFloatingView, layoutParams);
}
@Override
public void onDestroy() {
super.onDestroy();
if (mFloatingView != null) {
mWindowManager.removeView(mFloatingView);
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
```
在上面的代码中,我们使用 `WindowManager.LayoutParams` 对象设置了悬浮窗的边距。我们还使用 `GradientDrawable` 对象设置了悬浮窗的边框颜色。您可以根据需要自定义这些值。
阅读全文