Android全屏,隐藏状态栏和标题栏,本来以为这个功能很简单,不必拿出来说,但这个问题让我在互联网上找了N多例子,花了数个小时,看来还是有必要好好说说的。
网络上的许多方案都是正确的,但要放到合适的环境里才起作用。出现了下面这几种情况。
1、看第一个出问题的,直接使用android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen",但等我的是一个错误
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jianchi.fsp.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
错误信息如下
java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
看到错误了,看出来了,说让我们使用Theme.AppCompat theme,看来Theme.Black.NoTitleBar.Fullscreen在继承了AppCompatActivity的Activyty中会出问题。
2、将上面的代码都删除了,然后就代码来隐藏状态栏和标题栏。代码如下
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window window = getWindow();
//隐藏标题栏
requestWindowFeature(Window.FEATURE_NO_TITLE);
//隐藏状态栏
//定义全屏参数
int flag=WindowManager.LayoutParams.FLAG_FULLSCREEN;
//设置当前窗体为全屏显示
window.setFlags(flag, flag);
setContentView(R.layout.activity_main);
}
}
运行一下,状态栏真的没有了,但标题栏仍然在哪里。为什么标题栏还在哪里?肯定有些情况下是可以的!不再研究它了。
又查到下面的代码
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
终于标题栏ActionBar消失了。
推荐方法:在自定义的styles中设置隐藏状态栏和标题栏的theme,并在AndroidManifest.xml文件中的application或某个activity中设置。
styles文件如下
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="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="AppTheme.NoBar">
<item name="windowNoTitle">true</item>
<item name="android:windowFullscreen">true</item>
</style>
</resources>
AndroidManifest.xml文件如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jianchi.fsp.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity" android:theme="@style/AppTheme.NoBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
实现状态栏和标题栏终于消失了,效果如下图
我建了一个Git仓库,存放我尝试过的例子,完整 代码都放在那里。
https://code.youkuaiyun.com/do168/androidtestcenter
欢迎下载