Home > Enterprise >  Why does view visibility change to GONE after migrating to Kotlin?
Why does view visibility change to GONE after migrating to Kotlin?

Time:01-09

I am adding an removing a custom dialog using the root layout in the following code

fun addToRoot(view: View) {
    (findViewById<View>(android.R.id.content) as ViewGroup).addView(view)
}

Removing the view

fun removeFromRoot(view: View) {
    (findViewById<View>(android.R.id.content) as ViewGroup).removeView(view)
}

The view is shown ok the first time but on calling addToRoot a second time, I need to set view visibility to VISIBLE as its GONE after being removed. How is this happening considering this is the same code I was using in Java, I just migrated to Kotlin and had to find the bug where the view is not showing on the second call.

CodePudding user response:

I doubt that the view is being made gone by the code you posted. If we decompile the code to Java, we see the following:

   public final void addToRoot(@NotNull View view) {
      Intrinsics.checkNotNullParameter(view, "view");
      View var10000 = this.findViewById(16908290);
      if (var10000 == null) {
         throw new NullPointerException("null cannot be cast to non-null type android.view.ViewGroup");
      } else {
         ((ViewGroup)var10000).addView(view);
      }
   }

   public final void removeFromRoot(@NotNull View view) {
      Intrinsics.checkNotNullParameter(view, "view");
      View var10000 = this.findViewById(16908290);
      if (var10000 == null) {
         throw new NullPointerException("null cannot be cast to non-null type android.view.ViewGroup");
      } else {
         ((ViewGroup)var10000).removeView(view);
      }
   }

I am guessing that this looks very similar to your Java code ignoring the checks introduced by Kotlin.

  • Related