Create two-way binding with Android Data Binding

前端 未结 6 1326
情深已故
情深已故 2020-12-08 06:33

I have implemented the new Android data-binding, and after implementing realised that it does not support two-way binding. I have tried to solve this manually but I am strug

6条回答
  •  攒了一身酷
    2020-12-08 07:11

    I struggled to find a full example of 2-way databinding. I hope this helps. The full documentation is here: https://developer.android.com/topic/libraries/data-binding/index.html

    activity_main.xml:

    
    
        
            
        
    
        
    
            
    
    
            
    
            

    Item.java:

    import android.databinding.BaseObservable;
    import android.databinding.Bindable;
    
    public class Item extends BaseObservable {
        private String name;
        private Boolean checked;
        @Bindable
        public String getName() {
            return this.name;
        }
        @Bindable
        public Boolean getChecked() {
            return this.checked;
        }
        public void setName(String name) {
            this.name = name;
            notifyPropertyChanged(BR.name);
        }
        public void setChecked(Boolean checked) {
            this.checked = checked;
            notifyPropertyChanged(BR.checked);
        }
    }
    

    MainActivity.java:

    public class MainActivity extends AppCompatActivity {
    
        public Item item;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            item = new Item();
            item.setChecked(true);
            item.setName("a");
    
            /* By default, a Binding class will be generated based on the name of the layout file,
            converting it to Pascal case and suffixing “Binding” to it.
            The above layout file was activity_main.xml so the generate class was ActivityMainBinding */
    
            ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
            binding.setItem(item);
        }
    
        public void button_onClick(View v) {
            item.setChecked(!item.getChecked());
            item.setName(item.getName() + "a");
        }
    }
    

    build.gradle:

    android {
    ...
        dataBinding{
            enabled=true
        }
    
    }
    

提交回复
热议问题