Is it possible to pass custom arguments to onClick
method using the Data Binding Library? I have my layout xml file where I need to use the onClickListener:
You have a presenter or handler class like below
public class Presenter {
public void onSaveClick(View view, Task task){}
}
Now take variable of type Presenter
in your layout. and set click like below.
You can add any more arguments in this.
Please note that, you have to set these data variables. Like
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setTask(task);
binding.setPresenter(presenter);
Create a variable type of your Activity / Fragment
and make method in your activity which you want to call from binding layout. and don't forget to call setActivity(YourActivity.this)
from Activity.
public class MainActivity extends AppCompatActivity {
public void onSaveClick(View view, Task task) {
System.out.println("MainActivity.onSaveClick");
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setActivity(this);
binding.setTask(task);
}
}
Further reading Android DataBinding documentation
There are many other ways to set click, check this answer.