2

I am following the 'Developing android apps with Kotlin' beginner course from Udacity and stumbled upon something strange.

I have the following onCreate function in my MainActivity file:

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
}

The layout looks like this:

enter image description here

Here I use an integervalue to reference my view. When I change this to use a (from what I understood more modern) viewbinding, my layout doesn't center anymore. The code now looks like this:

private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityMainBinding.inflate(layoutInflater)
    val view = binding.root

    setContentView(view)
}

And the layout looks like this:

enter image description here

The corresponding xml file remains unchanged and looks like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:textSize="30sp"
        android:text="1" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/roll" />

</LinearLayout>

I've tried to google why this happens, but couldn't find anything. Does anyone know why this happens and how I can solve it?

JXD
  • 164
  • 7

0 Answers0