Android自定义Activity主题

最近做到一个功能,需要弹窗的效果,但是弹窗用起来实在没有Activity方便,可扩展性太小了,于是只好用Activity

但问题又来了,由于需要显示的内容并不多,无法占满整个Activity,而Activity默认的大小是全屏,导致视觉效果大大受损。

那么我们能不能想办法使得Activity拥有弹窗的视觉效果呢?

下面bill分享一下如何自定义Activity的主题,使得它看起来像一个弹窗。

首先,我们在res/drawable文件夹下建立一个名为my_bg的新xml配置文件,内容如下

 
  
  1. <?xml version="1.0" encoding="utf-8"?> 
  2.  
  3. <shape xmlns:android="http://schemas.android.com/apk/res/android"> 
  4.   <!-- 背景颜色 --> 
  5.   <solid android:color="#a060ff" /> 
  6.  
  7.   <!-- 3D效果 --> 
  8.   <stroke android:width="3sp" color="#c0ffff" /> 
  9.  
  10.   <!-- 角 --> 
  11.   <corners android:radius="10sp" /> 
  12.   <padding android:left="10sp" android:top="10sp" android:right="10sp" 
  13.     android:bottom="10sp" /> 
  14.  
  15. </shape> 

然后,在res/value文件夹下建立名为stylexml配置文件,内容如下

 

 
  
  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <resources> 
  3.  
  4.     <!-- 定义一个样式,继承android系统的对话框样式 android:style/Theme.Dialog --> 
  5.     <style name="my_theme" parent="android:style/Theme.Dialog"> 
  6.         <item name="android:windowBackground">@drawable/my_bg</item> 
  7.     </style> 
  8.  
  9. </resources> 

最后,在AndroidManifest.xml中将本Activity的主题设置为我们的自定义主题即可

 

 
  
  1. <activity android:name=".CustomActivityActivity" 
  2.     android:label="@string/app_name" android:theme="@style/my_theme"> 
  3.     <intent-filter> 
  4.         <action android:name="android.intent.action.MAIN" /> 
  5.         <category android:name="android.intent.category.LAUNCHER" /> 
  6.     </intent-filter> 
  7. </activity>