Using DataBinding library for binding events

前端 未结 9 720
小鲜肉
小鲜肉 2020-12-05 01:52

I\'m trying to bind events with views in xml using DataBinding Library shipped with Android M. I\'m following examples from Android Developers and implement

9条回答
  •  隐瞒了意图╮
    2020-12-05 02:23

    I'm posting this just to cover both ways to achieve this. 1. by Listener binding 2. by method refernce

    layout:

    
    
    
            
            
    
    
    
    
        

    Activity:

    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            ActivityMainBinding binding =
                    DataBindingUtil.setContentView(this, R.layout.activity_main);
            MyPresenter presenter = new MyPresenter();
            User user = new User("Alex","RJ")
            binding.setUser(user);
            binding.setHandlers(presenter);
        }
    

    MyPresenter:

    public class MyPresenter{
    
    //using listener binding
    public void onLisClick(User user){
    //do something..
    }
    
    
    //using method reference
    public void onButtonClicked(View view){
    
    // do something
    }
    
    }
    

    Note:
    1.While using method reference the method signature should be same as you would write for any other onClick's method ie public and View as parameter.

    2.While using listener binding you have benefit that you can directly pass the Object also if you want and do any operation.

提交回复
热议问题