Search code examples
androidbutterknife

How to bind a listener at run-time with Butter Knife?


Is it possible to bind a listener, such as onclick, at run-time with Butter Knife? I want to pass views, determined at run-time, to a method, and within that method bind a listener to them. I know how to accomplish what I want to do by normal means, so I'm strictly asking about Butter Knife.


Solution

  • Retention policy of Butterknife annotations is CLASS which means that fields annotated are identified (as annotated) by the compiler but not by the virtual machine. Binding of the values happens runtime. This means that all fields and methods are annotated upfront and later Butterknife has a map of all fields and methods with generated classes that need to be bind. Butterknife TL;DR

    Calling ButterKnife.bind(mRequiredView) will attempt to bind methods/fields in that view. Please be aware that if the view id is not existing most obviously the Butterknife will complain.

    Another way of doing so, is wrapping your method inside another (inner) class that will work as target object.

    private static class BindWrapper{
    
      @OnClick(R.id.view_later_to_be_bind)
      public void onClickedView(View v){
    
    
      }
    
    }
    

    Instance of that helper class will be used to bind views like:

    //somewhere in the code where we need to bind the listener
    BindWrapper target = new BindWrapper();
    ButterKnife.bind(target, mRequiredView)
    

    Not really elegant solution.