简体   繁体   English

如何在 Activity 中将 Butterknife 与 onClickListener 一起使用?

[英]How to use Butterknife with onClickListener in Activity?

I'm looking the answer how to make onClickListener button located in Recycleview Item using Butterknife.我正在寻找如何使用 Butterknife 制作位于 Recycleview Item 中的 onClickListener 按钮的答案。 I know how to do it without Butterknife, but I can't find anything with Bt.我知道没有 Butterknife 怎么办,但是我找不到 Bt 的任何东西。 Does Bt supports this? Bt支持吗?

Try to learn from the sample code at official site If you want to implement the click logic in the activity then here are the steps.尝试从官方网站的示例代码中学习如果您想在活动中实现点击逻辑,那么这里是步骤。

1 Create an interface 1 创建接口

    public interface ClickHandler{
             void onClick(int position);
         }

2 Implement CLickHandler in activity 2 在activity中实现CLickHandler

    MainActivity extends AppCompatActivity implements ClickHandler{
    ...
    public void onclick(int position){
        Log.d("Check","Clicked at" + position);
    }
    ...
    adapter = new MyAdapter(this);//Pass the reference to activity as it implements the clickhandler.
    ...

} }

3 Now your adapter has the reference for clickhandler. 3 现在您的适配器具有 clickhandler 的参考。 Similarly pass it to the viewholder and call the onCLick method from there.类似地将它传递给 viewholder 并从那里调用 onCLick 方法。

    class ViewHolder {
        @BindView(R.id.title) TextView name;
        @BindView(R.id.job_title) TextView jobTitle;
        ClickHandler clickHandler;

        public ViewHolder(View view, ClickHandler) {
          ButterKnife.bind(this, view);
          this.clickHandler = clickHandler;
        }

        @OnClick(R.id.submit)
         public void submit(View view) {
           if(clickHandler(!=null){
              clickHandler.onClick(getAdapterPosition());
           }
        }
      }
' class ViewHolder {
    @BindView(R.id.title) TextView name;
    @BindView(R.id.job_title) TextView jobTitle;

    public ViewHolder(View view) {
      ButterKnife.bind(this, view);
    }

    @OnClick(R.id.submit)
     public void submit(View view) {
       // TODO submit data to server...
    }
  }'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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