使用dataBinding

1. 在module的buil.gradle文件里面开启对databinding的支持.

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

2.修改布局文件,将布局xml修改成dataBinding格式





    
        

    

    

        

    

3.创建module.

public class User extends BaseObservable {
    public String name;
    public String position;

    @Bindable
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
        notifyPropertyChanged(BR.name);
    }

    @Bindable
    public String getPosition() {
        return position;
    }

    public void setPosition(String position) {
        this.position = position;
        notifyPropertyChanged(BR.position);
    }
}

4.使用dataBinding

public class TestActivity extends AppCompatActivity {

    private ActivityTestBinding activityTestBinding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityTestBinding = DataBindingUtil.setContentView(this,R.layout.activity_test);
        User user = new User();
        user.setName("fdsfd");
        activityTestBinding.setU(user);
        //试试修改user中的name属性 看ui会不会发生变化吧
        new Thread(){
            @Override
            public void run() {
                for (int i = 0; i < 10; i++) {
                    try {
                        Thread.sleep(1000);
                        user.setName(user.getName()+1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }


            }
        }.start();

    }
}     

你可能感兴趣的:(使用dataBinding)