MainActivityBinding.inflate(getLayoutInflater())页面未更新

时间:2016-05-03 04:21:02

标签: android android-databinding

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main2);
    Main2Binding binding1 =  Main2Binding.inflate(getLayoutInflater());
    User user = new User("Test", "User");
    MyHandlers myHandlers = new MyHandlers(this);
    MyStringUtils myStringUtils=  new MyStringUtils();
    binding1.setUser(user);
    binding1.setHandlers(myHandlers);
}

页面未更新,

MainActivityBinding binding1 = DataBindingUtil.setContentView (this, R.layout.main_activity); there is no problem

如何解决这个问题?

2 个答案:

答案 0 :(得分:4)

通过inflate方法使用DataBinding的正确方法

@Override
protected void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  
    //setContentView(R.layout.main2);// comment it
    Main2Binding binding1 = Main2Binding.inflate(getLayoutInflater());
    setContentView(binding1.getRoot());
    ...
}

答案 1 :(得分:0)

如果您想使用Activity绑定布局,则需要使用

MainActivityBinding binding1 = DataBindingUtil.setContentView (this, R.layout.main_activity);

但是当您使用Fragment时,可以使用inflate

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    MainActivityBinding binding = DataBindingUtil.inflate(inflater, R.layout.main_activity, container, false);
}

注意:绑定名称将基于布局名称,如果布局文件名为activity_main.xml,则绑定将为ActivityMainBinding。