onClick in Button do not work use Data Binding

Viewed 11327

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");
    }
2 Answers

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();
     }
}
Related