将Activity设置成窗口模式有两种方法,一种是利用系统提供的theme在清单配置文件中设置当前Activity的theme属性。另一种就是根据项目的需求自定义主题。
第一种方法:
在AndroidManifest.xml清单配置文件中修改当前Activity的theme属性
android:theme="@style/Theme.AppCompat.Light.Dialog"
完整的AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.zwb.floatactivity">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.AppCompat.Light.Dialog">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
运行效果图:
第二种方法就是根据项目中的需求,自定义主题
styles.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="Theme.FloatActivity" parent="Theme.AppCompat.Light.Dialog">
<item name="android:windowBackground">@drawable/float_box</item>
</style>
</resources>
其中Theme.FloatActivity就是我们自定义的属性。在drawable资源文件夹下新建一个样式文件,来设置我们自定义主题的样式
float_box.xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="@color/colorAccent"/>
<stroke android:width="3dp" android:color="#000000"/>
<corners android:radius="5dp"/>
<padding android:bottom="10dp" android:left="10dp" android:right="10dp" android:top="10dp"/>
</shape>
最后,在清单配置文件中,将当前的Activity的theme属性设置为我门自定义的theme就可以了
android:theme="@style/Theme.FloatActivity"
自定义的运行效果如下: