LoginSignup
13
19

More than 5 years have passed since last update.

使用しているテーマを崩さずに透明なActivityを作る方法

Posted at

訳あってAlertDialogをメインとは別のActivityに表示し、かつ透過して裏のActivityが見えるように表示しなければならない時があった。

一番簡単な方法としてAndroidManifest.xmlに1行追記する方法があるが、これだとスタイルや文字色が使っていたテーマとは変わってしまう。
styles.xmlを編集して同じテーマで透過する方法を記載する。

アプリケーション詳細

Target Sdk Version : API 19:Android 4.4(KitKat)

AndroidManifest.xmlに追記する方法

AndroidManifest.xmlの透過したいActivityに次の1行を追記する。

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

これにより透過はされる。
しかし昔のデザインっぽく見える。

device-2016-05-07-151850_s.png

styles.xmlを編集して使用中のテーマと同じテーマで透過する方法

app>res>values>style.xmlのファイルを編集する。

自分の環境だと、デフォルトでBase.Theme.AppCompat.Light.DarkActionBarを使っていた。

styles.xml
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Base.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>
</resources>

透過するには以下の3行をstyle内に追記する。

<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowTranslucentNavigation">true</item>

デフォルトのスタイルに追記してもいいし、新たなスタイルを作っても良い。
自分はデフォルトのスタイルは別のActivityで使用していたので、新しく作ることにした。
style nameは重複しないようにTransparencyThemeと記述。

styles.xml
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Base.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="TransparencyTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowTranslucentNavigation">true</item>
    </style>

</resources>

これでAndroidManifest.xmlのactivity内で以下のように指定すれば透過されたテーマを使用できる。

AndroidManifest.xml
<activity
android:name=".SampleActivity"
android:theme="@style/TransparencyTheme"></activity>

device-2016-05-07-151949_s.png

これでBase.Theme.AppCompat.Light.DarkActionBarのテーマのまま透過したActivityを表示することができた。

以上

13
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
19