6

I started to learn Data Binding Library https://developer.android.com/topic/libraries/data-binding/index.html

I can not understand what not so do.

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

<data>
    <variable
        name="presenter"
        type="ua.com.it_st.ordersmanagers.activiteies.HistoryActivity"/>
</data>

<Button
    android:id="@+id/test"
    android:text="Start second activity"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:clickable="true"
    android:onClick="@{presenter::onHistoryClick}"
    />

public class HistoryActivity extends MvpAppCompatActivity implements HistoryView {

    @InjectPresenter
    HistoryPresenter historyPresenter;

    ActivityHistoryBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         binding = DataBindingUtil.setContentView(this, R.layout.activity_history);
    }

    public void onHistoryClick(View view) {
        Log.i("test ","test");
        binding.test.setText("test");
    }
JRG
  • 4,037
  • 3
  • 23
  • 34
Gennadii Ianchev
  • 129
  • 1
  • 2
  • 11

2 Answers2

14

You forgot to set the ViewModel to your binding. If you expect the onClick to be received in your activity, you have to do

binding.setPresenter(this)

although I would recommend calling the ViewModel in your XML file viewModel or activity (it's called presenter right now). If you want your presenter ot receive the onClick, change the ViewModel type in your layout from activity to presenter, implement the onClick method in your presenter, and do

binding.setPresenter(presenter)
fweigl
  • 21,278
  • 20
  • 114
  • 205
4

Best way to do this is receive the onClick in the activity itself then pass that event into the function (if any) in the view model. You can do that in the following steps

1- In layout file, make change as:-

android:onClick="onClick"

2- In activity file, implement View.OnClickListener and register listener as binding.test.setOnClickListener(this)

3- Override the onClick method as

@Override
public void onClick(View view) {
    if(view == binding.test){
        //any utility method calls then calling the fun of view model
        (yourViewModel).onHistoryClick();
     }
}
striker
  • 560
  • 6
  • 13
  • 2
    What do you mean by `binding.test` here? – sud007 Nov 04 '19 at 09:43
  • 1
    we are registering the listener for the given button which has id "test"....since it's view model implementation so we are doing through binding (data binding) – striker Nov 04 '19 at 09:47
  • I know this is an old post, but i'm curious why you suggest this is the "best" way? Is it just easier to maintain? Seems like setting the onClick attribute right inside the layout xml file involves less lines of code – Carl Rossman Nov 28 '20 at 19:32