How to set Android DataBinding in nested layouts

前端 未结 2 1437
故里飘歌
故里飘歌 2021-02-07 21:07

I was just reading about data binding feature in android. I was trying to bind a view from a nested layout. My activity is android\'s default template of DrawerMenuActivit

2条回答
  •  醉酒成梦
    2021-02-07 21:39

    DataBindingUtils.setContentView() does exactly how it is named: It sets the current view to the given parameter. I don't think you want your AppBar as the whole view, or do you?

    Nevertheless, I assume that you include your layouts in your layout_activity_main.xml. George Mount has written a whole blog post about this feature. The code examples are from this post.

    The first example would be your layout_activity_main.xml (Or however you have named it), where you include your AppBar, your Content and so on.

    hello_world.xml
    
        
    
            
            
            
        
    
    
    
    included_layout.xml
    
    
        
    
    

    Now that the used layouts are clear, you'll need to jump into your ActivityMain, initialize the DataBinding and access your fields:

    //This works if you have used a variable in your  tag and you have built your project afterwards, if you don't have an activity
    HelloWorldBinding binding = HelloWorldBinding.inflate(getLayoutInflater());
    
     //if you have an activity, you can use setContentView from the DataBindingUtils. Don't forget to delete the generic setContentView
    HelloWorldBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_my_activity);
    
    
    //Once you have accomplished the above, you can access your data-bound fields like this:
    binding.hello.setText(“Hello”);
    binding.world1.world.setText(“First World”);
    binding.world2.world.setText(“Second World”);
    

    It is important to set Ids to your tags to access them correctly i your Activity.

提交回复
热议问题