我想在另一个活动之上创建一个透明的活动。
我怎样才能做到这一点呢?
我想在另一个活动之上创建一个透明的活动。
我怎样才能做到这一点呢?
当前回答
我想补充一点,因为我也是一个新的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”。我想我也应该提到这一点,以帮助其他人。
其他回答
在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>
你可以从你的活动中删除setContentView(r.b ayout. mlayout),并设置主题为android:theme="@style/AppTheme.Transparent"。查看这个链接了解更多细节。
注1:在Drawable文件夹中创建test.xml并复制以下代码
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<stroke android:width="2dp" />
<gradient
android:angle="90"
android:endColor="#29000000"
android:startColor="#29000000" />
<corners
android:bottomLeftRadius="7dp"
android:bottomRightRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp" />
</shape>
//注:角和形状按您的要求来定。
//注释2:创建xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/test"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1.09"
android:gravity="center"
android:background="@drawable/transperent_shape"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
其他解决方案对我有用,但我注意到一个问题,可能会影响一些人。当我像这样开始我的活动时:
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似乎已经解决了这个问题
将半透明主题分配给你想要在项目的Android清单文件中透明的活动:
<activity
android:name="YOUR COMPLETE ACTIVITY NAME WITH PACKAGE"
android:theme="@android:style/Theme.Translucent.NoTitleBar" />