Android4.4+ 实现半透明状态栏(Translucent Bars)

时间:2022-07-27
本文章向大家介绍Android4.4+ 实现半透明状态栏(Translucent Bars),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Android从4.4(KitKat) 开始进行了一些视觉上的改善和提升,其中包括让状态栏(Status Bar)和下方导航栏(Navigation Bar)进行半透明处理,可以使APP内容向上下延伸,使整个画面的利用度大幅度提升,本篇就来说说这个“半透明状态栏”(Translucent Bars)。

简单做了个Demo效果如下图

*这里解释个误区,国内开发者和设计师经常把这种半透明效果称为沉浸式状态栏这是不对的, 沉浸式Immersive mode,官方解释为hiding all system UI根本不是这种半透明的效果。

下面说说如何使用这种效果:

1、在onCreate里面代码设置半透明的属性,由于只有Android 4.4以上才支持这种效果,所以代码需要判断下

if(Build.VERSION.SDK_INT  = Build.VERSION_CODES.KITKAT) {
      //透明状态栏
      getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
      //透明底部导航栏
      getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
     }

2、在这个界面上我去掉了Actionbar,实现方式有很多,这里我使用的是在Style里去掉。

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar" 
    <!-- Customize your theme here. -- 
  </style 

3、这个部分需要留意一下,如果希望APP的显示内容正常和滚动透明化需要加上android:fitsSystemWindows=”true”和android:clipToPadding=”false”的属性,建议你把这两个属性好好试试加上与否的区别。

<ScrollView 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:fitsSystemWindows="true"
  android:clipToPadding="false"
  android:background="#795548"
  tools:context=".DefaultActivity"  

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="18sp"
    android:textColor="#ffffff"
    android:text="@string/str" / 

</ScrollView 

这样一个简单的半透明化效果就实现了

详细源码:

Layout

<ScrollView 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:fitsSystemWindows="true"
  android:clipToPadding="false"
  android:background="#795548"
  tools:context=".DefaultActivity"  

  <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="18sp"
    android:textColor="#ffffff"
    android:text="@string/str" / 

</ScrollView 

Style

<resources 

  <!-- Base application theme. -- 
  <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar" 
    <!-- Customize your theme here. -- 
  </style 

</resources 

MainActivity

public class MainActivity extends AppCompatActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(Build.VERSION.SDK_INT  = Build.VERSION_CODES.KITKAT) {
      //透明状态栏
      getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
      //透明导航栏
      getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
     }

    setContentView(R.layout.activity_main);



  }

以上就是本文的全部内容,希望对大家的学习有所帮助。