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

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


当前回答

其他解决方案对我有用,但我注意到一个问题,可能会影响一些人。当我像这样开始我的活动时:

Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);

而不是像这样的一行字

startActivity(new Intent(this, MainActivity.class));

我只得到黑色的背景,这很痛苦。我还没有弄清楚是什么导致了这个,我猜这是设备相关的(在小米上测试)。传递值也需要像这样。

startActivity(new Intent(this, MainActivity.class)
                            .putExtra("SOME_VALUE", value)
                            .putExtra("ANOTHER_VALUE", value2));

编辑: 将父样式更改为Theme.AppCompat.Light.NoActionBar似乎已经解决了这个问题

其他回答

它是这样的:

<activity android:name=".usual.activity.Declaration" 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"

有两种方法:

使用主题。NoDisplay 使用Theme.Translucent.NoTitleBar

使用主题。NoDisplay仍然可以工作,但只适用于旧的Android设备。Android 6.0及以上版本,使用Theme。没有调用onCreate()中的finish()(或者,从技术上讲,在onResume()之前)NoDisplay将使应用程序崩溃。这就是为什么建议使用theme .半透明。NoTitleBar,不受此限制。”

如果你正在使用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"

更多细节请阅读这篇文章