【Android】打开新界面还能看到上一个界面内容

第一种继承activity

【功能介绍】

打开新界面还能看到上一个界面内容,上一个界面变暗,而且只是能看到,无法响应上一个界面的任何内容。

【原理说明】

实际上是打开了一个新的Activity,这个新的Activity是透明的,然后设置新Activity的最外层布局的Background设置成半透明

【具体操作】

1、首先在AndroidMaifest中定义新Activity的Them为透明主题。

(1)全屏、无标题栏

<activity

android:name=".testActivity"

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

(2)非全屏、无标题栏    常用

<activity
android:name=".testActivity"
android:theme="@android:style/Theme.Translucent.NoTitleBar" />

(3)非全屏、有标题栏

<activity

android:name=".testActivity"

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

2、在新Activity.java中修改继承类为Activity类。

public class SmallActivity extends Activity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_small);
    }
}

3、设置layout最外层布局的background。

android:background="#55000000"

55是不透明数值,00是全透明,ff是不透明。

第二种继承AppCompatActivity

添加关闭打开activity动画会比较好看

// activity开启无动画

overridePendingTransition(0, 0);

public class SmallActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_small);
    }
}

当Activity继承于AppCompatActivity时,只能使用Theme.AppCompat下的主题。而这些主题并没有Translucent.提示错误: 
java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

可以采用自定义主题来弥补AppCompat中无透明主题,方式如下:

<!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/theme</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:background">@color/translate</item>
    </style>
    <!--全屏加透明-->
    <style name="TranslucentFullScreenTheme" parent="FullScreenTheme">
        <item name="android:windowBackground">@color/translate</item>
        <item name="android:windowIsTranslucent">true</item>
    </style>
    <!--全屏-->
    <style name="FullScreenTheme" parent="AppTheme">
        <item name="android:windowFullscreen">true</item>
        <item name="android:windowNoTitle">true</item>
    </style>
    <!--透明,有任务栏电量时间等-->
    <style name="NoTitleTranslucentTheme" parent="AppTheme">
        <item name="android:windowNoTitle">true</item>
        <item name="android:windowBackground">@color/translate</item>
        <item name="android:windowIsTranslucent">true</item>
    </style>
 

猜你喜欢

转载自blog.csdn.net/zhw0596/article/details/82154498