Android:透明活动问题

2024-05-14

最近,在我们的一款生产应用程序上,透明活动已停止工作。 我的意思是它变成了黑色背景而不是透明背景。当我将活动的背景颜色设置为纯色(即红色、绿色等)时,它的应用不会出现问题。 该问题可能是由于迁移到 AndroidX 引起的,但我没有这方面的证据。

经过数小时的调试、测试和阅读相关 SO 主题后,我终于能够确定问题发生的情况。

我的测试环境是非常简单的干净项目,有两项活动 https://github.com/mirokolodii/DebugTransparentActivity(您可以在链接下查看完整代码)。

工作状态条件

仅当我的“themes.xml”文件非常简单时,我才能使第二个活动透明。您可以在后台看到第一个活动:

非工作状态的条件

添加一个简单的样式就足够了,即使内部没有项目并且没有父项,也可以使背景变为黑色而不是透明:

这是我的“themes.xml”:

<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Theme.MyApplication" parent="Theme.AppCompat.Light">
        <item name="android:windowBackground">@android:color/white</item>
    </style>

    <style name="Transparent" parent="Theme.AppCompat.Dialog">
        <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>
        <item name="android:windowTranslucentStatus">true</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
    </style>

    <!--    By removing this style I can make transparent activity to work -->
    <style name="ScrollViewStyle" />

</resources>

和“AndroidManifest.xml”:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapplication">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.MyApplication">
        <activity
            android:name=".SecondActivity"
            android:label="@string/title_activity_second"
            android:theme="@style/Transparent" />
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_first">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

我希望有人能够帮助我获得这种奇怪行为的技术解释。


作为解决方法,我可以通过将其主题设置为来使活动透明android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"直接在清单中。请注意“直接”,因为如果我什至以上述主题作为父主题创建自定义空主题,它将不起作用。 但这个解决方案有局限性:

  • 无法自定义行为,例如使用对话框进入/退出过渡动画等。
  • Activity 应该扩展 Android Activity,而不是 AppCompatActivity。
  • 我还必须为此活动的根视图设置透明背景以实现透明度。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android:透明活动问题 的相关文章

随机推荐