简体   繁体   中英

How to initialize ViewBinding?

How to initialize VievBinding? In AppCompactActivity version 1.0.0, it became possible to pass a layout to the parent constructor so that you would not write OnCreateView. I do so, but then I want to use VievBinding, but it doesn't work for me. Text is not displayed. What can be done?

    class MainActivity : AppCompatActivity(R.layout.activity_main) {

    override fun onStart() {
        super.onStart()
        var binding = ActivityMainBinding.inflate(layoutInflater)
        binding.hello.text = "Hello"
    }
}

class MainActivity : AppCompatActivity(R.layout.activity_main) {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.bind(findViewById(Window.ID_ANDROID_CONTENT).getChildAt(0))
    }

Although it's easier if you rely on __Binding.inflate() .

class MainActivity : AppCompatActivity {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater, R.layout.activity_main)
        setContentView(binding.root)
    }

Layout inflation should not be in onStart . It goes in onCreate in Activity, and onCreateView in Fragment.

var binding = ActivityMainBinding.inflate(layoutInflater)

This will inflate the layout again and you will get a different instance of the views than what is already set in the activity

Try using the below code to bind the activity view to the binder. Where ROOT_VIEW_ID is view id of root view in your layout

var binding = ActivityMainBinding.bind(findViewById(ROOT_VIEW_ID))*
*binding.hello.text = "Hello"

// Activity class
override fun onCreate(savedInstanceState: Bundle?) {
   super.onCreate(savedInstanceState);

   val binding:YourActivityLayoutBinding = 
         DataBindingUtil.setContentView(this, R.layout.your_activity_layout);
}

Layout views in xml should be surrounded by <layout> tag

<layout>
...// your activity view layout
</layout>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM