我想在另一个活动之上创建一个透明的活动。

我怎样才能做到这一点呢?


当前回答

如果你正在使用AppCompatActivity,那么在styles.xml中添加这个

<style name="TransparentCompat" parent="@style/Theme.AppCompat.Light.DarkActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:colorBackgroundCacheHint">@null</item>
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowAnimationStyle">@android:style/Animation</item>
</style>

在清单文件中,您可以像这样将此主题添加到活动标签

android:theme="@style/TransparentCompat"

更多细节请阅读这篇文章

其他回答

在onCreate函数中,在setContentView的下面,添加这一行:

getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

我想补充一点,因为我也是一个新的Android开发人员。公认的答案很好,但我确实遇到了一些麻烦。我不确定如何在colors.xml文件中添加颜色。下面是应该怎么做:

colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
     <color name="class_zero_background">#7f040000</color>
     <color name="transparent">#00000000</color>
</resources>

在我最初的colors.xml文件中,我有标签“drawable”:

<drawable name="class_zero_background">#7f040000</drawable>

所以我对颜色也这样做了,但我不理解“@color/”引用意味着在XML中寻找标记“color”。我想我也应该提到这一点,以帮助其他人。

为它指定半透明主题

android:theme="@android:style/Theme.Translucent.NoTitleBar"

在res/values/styles.xml文件中添加以下样式(如果没有,创建一个)。这是一个完整的文件:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <style name="Theme.Transparent" parent="android:Theme">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:backgroundDimEnabled">false</item>
  </style>
</resources>

@color/transparent的值是我放在res/values/color.xml文件中的颜色值#00000000。在以后的Android版本中也可以使用@android:color/transparent。)

然后将样式应用到您的活动,例如:

<activity android:name=".SampleActivity" android:theme="@style/Theme.Transparent">
...
</activity>

只需将下面一行添加到清单文件中的activity标记中,它需要看起来透明。

android:theme="@android:style/Theme.Translucent"