Fusion method of background map and status bar based on Android

  • 2021-08-12 03:24:38
  • OfStack

Let's look at 1 code first:


public class MainActivity extends AppCompatActivity {
  ...
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT >= 21){
      View decorView = getWindow().getDecorView();
      decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
      getWindow().setStatusBarColor(Color.TRANSPARENT);
    }
    setContentView(R.layout.activity_main);
      ...
  }

Since this function is supported by Android5.0 and above systems, we first judge the system version number in the code, and only when the version number is greater than or equal to 21, that is, when the system is 5.0 and above, the following code will be executed.

Then we call the getWindow (). getDecorView () method to get the currently active DecorView, and then call its setSystemUiVisibility () method to change the display of the system UI. Passing View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN and View.SYSTEM_UI_FLAG_LAYOUT_STABLE means that the active layout will be displayed on the status bar. Finally, we call setStatusBarColor () method under 1 to set the status bar to transparent color.

Only these codes can achieve the effect of merging the background map and status bar into one.

However, if you run the program 1, you will find that there are still some problems. The head layout of the interface is almost close to the system status bar. This is because the system status bar has become a part of our layout, so there is no room for it alone. Of course, this problem is also very easy to solve, with the help of android: fitsSystemWindows attribute.

See code:


<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:background="@color/colorPrimary">
    <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical"
      android:fitsSystemWindows="true">
    </LinearLayout>
</FrameLayout>

That's it.


Related articles: