Search code examples
androidkotlinandroid-viewbinding

In android studio(Kotlin), why ViewBinding and setOnApplyWindowInsetsListener conflicts?


When I use codes generated by android studio automatically and ViewBinding together, the programme will crash.

ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }// this is what android studio generate

val binding=ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

When I delete the first part( setOnApplyWindowInsetsListener ), the programme will run properly. I have no idea what's going wrong

here's what logcat says, I copy them all and the error is at the bottom

2024-07-18 11:20:36.777 20996-20996 ziparchive              com.example.uiwidgettest             W  Unable to open '/data/app/~~pqSil-xEI7VW0FmbjVGwVA==/com.example.uiwidgettest-Q-RcIuNwpvivt9LzMFW-IA==/base.dm': No such file or directory
2024-07-18 11:20:36.777 20996-20996 ziparchive              com.example.uiwidgettest             W  Unable to open '/data/app/~~pqSil-xEI7VW0FmbjVGwVA==/com.example.uiwidgettest-Q-RcIuNwpvivt9LzMFW-IA==/base.dm': No such file or directory
2024-07-18 11:20:36.873 20996-20996 nativeloader            com.example.uiwidgettest             D  Configuring clns-6 for other apk /data/app/~~pqSil-xEI7VW0FmbjVGwVA==/com.example.uiwidgettest-Q-RcIuNwpvivt9LzMFW-IA==/base.apk. target_sdk_version=34, uses_libraries=, library_path=/data/app/~~pqSil-xEI7VW0FmbjVGwVA==/com.example.uiwidgettest-Q-RcIuNwpvivt9LzMFW-IA==/lib/x86_64, permitted_path=/data:/mnt/expand:/data/user/0/com.example.uiwidgettest
2024-07-18 11:20:36.896 20996-20996 GraphicsEnvironment     com.example.uiwidgettest             V  Currently set values for:
2024-07-18 11:20:36.896 20996-20996 GraphicsEnvironment     com.example.uiwidgettest             V    angle_gl_driver_selection_pkgs=[]
2024-07-18 11:20:36.896 20996-20996 GraphicsEnvironment     com.example.uiwidgettest             V    angle_gl_driver_selection_values=[]
2024-07-18 11:20:36.896 20996-20996 GraphicsEnvironment     com.example.uiwidgettest             V  Global.Settings values are invalid: number of packages: 0, number of values: 0
2024-07-18 11:20:36.896 20996-20996 GraphicsEnvironment     com.example.uiwidgettest             V  Neither updatable production driver nor prerelease driver is supported.
2024-07-18 11:20:37.034 20996-20996 AppCompatDelegate       com.example.uiwidgettest             D  Checking for metadata for AppLocalesMetadataHolderService : Service not found
2024-07-18 11:20:37.157 20996-20996 le.uiwidgettest         com.example.uiwidgettest             W  Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (unsupported, reflection, allowed)
2024-07-18 11:20:37.159 20996-20996 le.uiwidgettest         com.example.uiwidgettest             W  Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (unsupported, reflection, allowed)
2024-07-18 11:20:37.163 20996-20996 TransactionExecutor     com.example.uiwidgettest             E  Failed to execute the transaction: tId:-695490178 ClientTransaction{
                                                                                                    tId:-695490178   transactionItems=[
                                                                                                    tId:-695490178     LaunchActivityItem{activityToken=android.os.BinderProxy@7bb8227,intent=Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.example.uiwidgettest/.MainActivity },ident=95817982,info=ActivityInfo{5dc30a0 com.example.uiwidgettest.MainActivity},curConfig={1.0 310mcc260mnc [en_US] ldltr sw411dp w411dp h731dp 420dpi nrml long port finger qwerty/v/v dpad/v winConfig={ mBounds=Rect(0, 0 - 1080, 1920) mAppBounds=Rect(0, 0 - 1080, 1920) mMaxBounds=Rect(0, 0 - 1080, 1920) mDisplayRotation=ROTATION_0 mWindowingMode=fullscreen mActivityType=undefined mAlwaysOnTop=undefined mRotation=ROTATION_0} s.8 fontWeightAdjustment=0},overrideConfig={1.0 310mcc260mnc [en_US] ldltr sw411dp w411dp h731dp 420dpi nrml long port finger qwerty/v/v dpad/v winConfig={ mBounds=Rect(0, 0 - 1080, 1920) mAppBounds=Rect(0, 0 - 1080, 1920) mMaxBounds=Rect(0, 0 - 1080, 1920) mDisplayRotation=ROTATION_0 mWindowingMode=fullscreen mActivityType=standard mAlwaysOnTop=undefined mRotation=ROTATION_0} s.3 fontWeightAdjustment=0},deviceId=0,referrer=com.android.shell,procState=2,state=null,persistentState=null,pendingResults=null,pendingNewIntents=null,sceneTransitionInfo=null,profilerInfo=null,assistToken=android.os.BinderProxy@9f86f5d,shareableActivityToken=android.os.BinderProxy@fa3f0d2,activityWindowInfo=ActivityWindowInfo{isEmbedded=false, taskBounds=Rect(0, 0 - 1080, 1920), taskFragmentBounds=Rect(0, 0 - 1080, 1920)}}
                                                                                                    tId:-695490178     ResumeActivityItem{mActivityToken=android.os.BinderProxy@7bb8227,procState=-1,updateProcState=false,isForward=true,shouldSendCompatFakeFocus=false}
                                                                                                    tId:-695490178     Target activity: com.example.uiwidgettest.MainActivity
                                                                                                    tId:-695490178   ]
                                                                                                    tId:-695490178 }
2024-07-18 11:20:37.163 20996-20996 AndroidRuntime          com.example.uiwidgettest             D  Shutting down VM
2024-07-18 11:20:37.166 20996-20996 AndroidRuntime          com.example.uiwidgettest             E  FATAL EXCEPTION: main
                                                                                                    Process: com.example.uiwidgettest, PID: 20996
                                                                                                    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.uiwidgettest/com.example.uiwidgettest.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnApplyWindowInsetsListener(android.view.View$OnApplyWindowInsetsListener)' on a null object reference
                                                                                                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4047)
                                                                                                        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:4234)
                                                                                                        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:112)
                                                                                                        at android.app.servertransaction.TransactionExecutor.executeNonLifecycleItem(TransactionExecutor.java:174)
                                                                                                        at android.app.servertransaction.TransactionExecutor.executeTransactionItems(TransactionExecutor.java:109)
                                                                                                        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:81)
                                                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2635)
                                                                                                        at android.os.Handler.dispatchMessage(Handler.java:107)
                                                                                                        at android.os.Looper.loopOnce(Looper.java:232)
                                                                                                        at android.os.Looper.loop(Looper.java:317)
                                                                                                        at android.app.ActivityThread.main(ActivityThread.java:8699)
                                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:580)
                                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:886)
                                                                                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setOnApplyWindowInsetsListener(android.view.View$OnApplyWindowInsetsListener)' on a null object reference
                                                                                                        at androidx.core.view.ViewCompat$Api21Impl.setOnApplyWindowInsetsListener(ViewCompat.java:4840)
                                                                                                        at androidx.core.view.ViewCompat.setOnApplyWindowInsetsListener(ViewCompat.java:2537)
                                                                                                        at com.example.uiwidgettest.MainActivity.onCreate(MainActivity.kt:18)
                                                                                                        at android.app.Activity.performCreate(Activity.java:8980)
                                                                                                        at android.app.Activity.performCreate(Activity.java:8958)
                                                                                                        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1526)
                                                                                                        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:4029)
                                                                                                        ... 13 more

Solution

  • The main reason of this crash is finding the view before you set the layout.

    findViewById(R.id.main)
    

    Solution

    1. Make sure your parent view in layout xml has main id.

    If it's auto-generated by IDE, it should automatically added like this.

    android:id="@+id/main"
    
    1. Set content view before setOnApplyWindowInsetsListener.
    val binding = ActivityMainBinding.inflate(layoutInflater)
    setContentView(binding.root)
    
    ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets - >
        val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
        v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
        insets
    }
    

    If you don't want to set id to your parent layout, you can still get parent view of your layout like this.

    findViewById(android.R.id.content)
    

    Or if you want to use view binding, you can use binding.root instead.

    Explanation

    When you create Empty views activity from IDE, it generated a full screen edge to edge activity like this.

    enableEdgeToEdge()
    setContentView(R.layout.activity_main)
    
    ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets - >
        val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
        v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
        insets
    }
    
    • enableEdgeToEdge() is a Kotlin extension that enables the edge-to-edge display (full screen) for your activity.

    • Since your activity is now edge to edge, you need to apply padding to your parent view so that its contents (child views) fit inside the system bars (status bars and navigation bars) and Toolbar.

    If you don't want to make your activity edge to edge, you can safely remove these auto generated codes.