2

如何使用 ButterKnife 注解消除以下初始化代码?

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);
}
4

2 回答 2

12

使用ButterKnife 7 API 中的 @BindDrawable。

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);
}

其他资源类型有@BindString、@BindInt、@BindDimen、@BindColor、@BindBool。

于 2015-07-07T14:17:05.073 回答
0

在 ButterKnife 中使用 @Bind 属性,如下所述。

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

并在调用 setContentView 方法后的 onCreate 中,使用 ButterKnife 的 bind 方法(如果您使用的是 Activity)。

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

如果您使用的是 Fragment,请使用以下代码初始化 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;
}
于 2015-09-15T02:10:49.053 回答