为什么使用View Binding更改布局?

实际代码:

我的主要活动:

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

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

        val rollButton = binding.rollButton
        rollButton.setOnClickListener { rollDice() }

        setContentView(binding.root)
    }

    private fun rollDice() {
        val randomDiceRoll = Random.nextInt(6) + 1
        Toast.makeText(this, randomDiceRoll.toString(), Toast.LENGTH_SHORT).show()
        binding.resultText.text = randomDiceRoll.toString()
    }

我的XML文件:

<?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:id="@+id/result_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/count"
        android:textSize="30sp" />

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

</LinearLayout>

Preview in android studio: Preview Actual layout in device: actual layout If I change setContentView(binding.root) to setContentView(R.layout.activity_main), the layout of Android Studio and the device become the same, but of course, the button doesn't work anymore...

Why does this happen? Why is ActivityMainBinding.inflate(layoutInflater) changing the layout? How to fix this?

谢谢

评论
语柳
语柳

据我所知,要启用数据绑定,您将不得不对xml进行修改。

I am referring to the Docs.

You will have to wrap your Layout into the <layout>- tag for databinding to work. I think this might cause your problem

点赞
评论