DataBinding入门四部曲

概念请移步:https://developer.android.com/topic/libraries/data-binding/#data_binding_layout_files

  • 一:build.gradle(Module:app) 启用databinding
android {
    ...

    dataBinding {
        enabled = true
    }
}

注意:Rebuild Project

  • 二:布局应用



    

        
    
    
    
    

        
        

        

    

  • 三:bean创建
public class User extends BaseObservable {

    private String name;

    public User(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

  • 四:绑定数据
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 无标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        // ActivityMainBinding
        // 代替原来的setContentView(R.layout.activity_main)方法
        ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        User user = new User("Hellow Android");
        // set方法是根据data标签下的variable名称自动生成的
        binding.setUser(user);
    }
}

赶快去试试吧。。。此文领进门,修行靠个人。

你可能感兴趣的:(Android)