app中有一个按钮,点击以后弹出一个按钮悬浮到所有app最上层,写出实现安卓代码
时间: 2024-05-02 07:18:08 浏览: 254
首先,在布局文件中定义悬浮按钮的样式:
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/floating_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Floating Button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="16dp"/>
</RelativeLayout>
```
然后,在Activity中实现悬浮按钮:
```
public class MainActivity extends AppCompatActivity {
private WindowManager windowManager;
private Button floatingButton;
private WindowManager.LayoutParams params;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取WindowManager
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
//创建悬浮按钮
floatingButton = new Button(this);
floatingButton.setText("Floating Button");
//设置悬浮按钮的参数
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
PixelFormat.TRANSLUCENT
);
//设置悬浮按钮的位置和大小
params.gravity = Gravity.TOP | Gravity.START;
params.x = 0;
params.y = 0;
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
//将悬浮按钮添加到WindowManager中
windowManager.addView(floatingButton, params);
//设置悬浮按钮的点击事件
floatingButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//TODO: 点击悬浮按钮的操作
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
//移除悬浮按钮
if (floatingButton != null) {
windowManager.removeView(floatingButton);
}
}
}
```
需要注意的是,在Android 8.0及以上的版本中,需要使用`WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY`来创建悬浮窗口。同时,需要在AndroidManifest.xml中添加`<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>`权限。
阅读全文