数据绑定:为什么RecyclerView.Adapter onClick事件不是火?

时间:2017-11-28 14:49:13

标签: android android-databinding

Android Studio 3.0,Java 8.

dataBinding { enabled = true }

这里是我的RecyclerView适配器代码(java文件):

    public class OfferSortAdapter extends RealmRecyclerViewAdapter<Offer, OfferSortAdapter.OfferViewHolder> {     

        @Override
        public OfferSortAdapter.OfferViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            OfferItemBinding offerItemBinding = OfferItemBinding.inflate(inflater, parent, false);
            return new OfferViewHolder(offerItemBinding.getRoot(), offerItemBinding);
   }      
        @Override
        public void onBindViewHolder(OfferSortAdapter.OfferViewHolder holder, final int position) {
            Offer offer = getItem(position);
            holder.offerItemBinding.setOffer(offer);
        }
        public static class OfferViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.imageViewPhoto)
            ImageView imageViewPhoto;    
            OfferItemBinding offerItemBinding; 

            private OfferViewHolder(View view, OfferItemBinding offerItemBinding) {
                super(view);
                this.offerItemBinding = offerItemBinding;
                ButterKnife.bind(this, view);
            }

            public void onClickImageViewPhoto(View view) {
                  // not call this method
            }
        }
    }

这里是xml布局文件:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">    
    <data>    
      <variable name="handlers"               type="myproject.OfferSortAdapter.OfferViewHolder" />
    </data>    
    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">    
        <ImageView
            android:id="@+id/imageViewPhoto"
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:onClick="@{handlers::onClickImageViewPhoto}"/>
</layout>

如您所见,我在xml布局上设置onClickHandler:@{handlers::onClickImageViewPhoto}

但是当我点击ImageView时,方法onClickImageViewPhoto不会调用。

1 个答案:

答案 0 :(得分:0)

在绑定类中设置Handler对象。

OfferItemBinding offerItemBinding = OfferItemBinding.inflate(inflater, parent, false);
OfferViewHolder offerViewHoder = new OfferViewHolder(offerItemBinding.getRoot(), offerItemBinding); 
offerItemBinding.setHandlers(offerViewHoder);
return offerViewHoder;

建议。

无需使用ButterKnife,因为您可以访问布局组件,例如

binidng.image_view_photo

请记住,这些字段是在蛇形情况下生成的。 imageViewPhoto将转换为image_view_photo