简体   繁体   中英

Android two way data binding with onclick() not working

I am trying to implement android two way databinding in my code. I am not able get onclick event for a textview which I have used for two way data binding for its text.

ps:

  1. I have enabled data binding
  2. I have set all the variable to binding as well

layout xml

        <TextView
                    android:id="@+id/likes"
                    android:clickable="true"
                    android:onClick="@{clickHandler::onClickEvents}"
                    android:text='@= 
 {com.coffeeshots.app.foodieapp.utils.Converter.convertIntToString(food.likes)}'
     </TextView>

`

databinding code

<data>
    <variable 
       name="food" 
       type="com.coffeeshots.app.foodieapp.model.Food"/>

    <import type="com.coffeeshots.app.foodieapp.utils.Converter"/>
   
    <variable 
       name="clickHandler" 
       type="com.coffeeshots.app.foodieapp.utils.ClickHandler"/>
</data>
   

onclick method

 public void onClickEvents(View view) {

          switch(view.getId()){
            case R.id.likes:
                if(!likesGiven){
                    likesGiven = true;
                    binding.likes.setText("1");
                    binding.dislikes.setClickable(false);
             }
                break;

          }
     

I think the problem is the way i inflate the layout, Can anyone help me here???

  LayoutInflater layoutInflater = getLayoutInflater();

     binding= DataBindingUtil.inflate(layoutInflater,R.layout.activity_add_food,null,false);
    
    setContentView(binding.getRoot());

Try this:

android:onClick="@{(view)-> clickHandler.onClickEvents(view)}"

Yes, your layout inflating is wrong. Do like this:

ActivityAddFoodBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_add_food);
binding.setClickHandler(new ClickHandler());

You can also find the related official example here: https://developer.android.com/topic/libraries/data-binding/expressions#binding_data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM