- 次文章只是记录如何在Android5.0以上版本改变状态栏颜色为透明色
- 首先新建个项目,项目只有一个页面,xml代码如下:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F54307"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#00FF40"
tools:ignore="MissingConstraints"
android:text="标题"/>
</android.support.constraint.ConstraintLayout>
-
允许后如图:
-
如图默认状态栏就是这个颜色,下面我们来设置透明状态栏
-
首先在style文件夹中新建一个style样式,代码如下:
<style name="StatusBarTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- 透明状态栏 -->
<item name="android:windowIsTranslucent">true</item>
</style>
- 接着我们在AndroidManifest文件中引用这个style文件,代码:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.fxx.statusbar">
<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/AppTheme">
<!-- 这里我们引用style文件 -->
<activity android:name=".MainActivity" android:theme="@style/StatusBarTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
- 在MainActivity代码如下:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//页面无标题
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
//透明状态栏
setStatusTransparency();
}
/**
* 透明状态栏
*/
private void setStatusTransparency() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
| WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
window.setNavigationBarColor(Color.TRANSPARENT);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window window = getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
}
}
- 然后我们再次运行一下看下效果图
- 如图我们已经看到状态栏的颜色已经是透明的了,但是呢,标题按钮的位置却与状态栏重叠了,这里我们只需要把按钮设置边距,大概30dp左右,再来运行一下看下效果图:
- 好了,效果图可以看到我们的按钮已经在状态栏下面了,由于Android机型太多,边距大小也不是固定的,需要自行检测,也可以再代码中动态设置边距,这里就不再讲解了~~