2

How to eliminate the following initialization code using ButterKnife annotations?

private Drawable mExpandDrawable;
private Drawable mCollapseDrawable;

void init() {
    mExpandDrawable = getResources().getDrawable(R.drawable.ic_expand_small_holo_light);
    mCollapseDrawable = getResources().getDrawable(R.drawable.ic_collapse_small_holo_light);
}
naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259

2 Answers2

12

Use @BindDrawable from ButterKnife 7 API.

import butterknife.BindDrawable;

@BindDrawable(R.drawable.ic_expand_small_holo_light)
protected Drawable mExpandDrawable;
@BindDrawable(R.drawable.ic_collapse_small_holo_light)
protected Drawable mCollapseDrawable;

void init() {
    ButterKnife.bind(this);
}

There are @BindString, @BindInt, @BindDimen, @BindColor, @BindBool for other resource types.

naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259
  • 1
    Note that the fields you are binding to cannot be private. They must have at least package visibility so the generated code can modify them. http://stackoverflow.com/questions/27244742/butterknife-view-injection – Derek Jul 08 '15 at 13:50
0

Use @Bind property in ButterKnife as mentioned below.

@BindDrawable(R.drawable.ic_expand_small_holo_light) Drawable mExpandDrawable;

and in onCreate after setContentView method is called, use bind method of ButterKnife (If you are using Activity).

@Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_activity);
    ButterKnife.bind(this);
    // TODO Use fields...
}

If you are using Fragment, use the below code to initialize ButterKnife:

@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fancy_fragment, container, false);
    ButterKnife.bind(this, view);
    // TODO Use fields...
    return view;
}
naXa stands with Ukraine
  • 35,493
  • 19
  • 190
  • 259
Sanal Varghese
  • 1,465
  • 4
  • 23
  • 46