android 注解框架ButterKnife使用

来源:转载

github地址:https://github.com/JakeWharton/butterknife

官方文档说明:http://jakewharton.github.io/butterknife/

基本使用:

下载:
1.https://repo1.maven.org/maven2/com/jakewharton/butterknife/7.0.1/butterknife-7.0.1.jar
grab via Maven:

com.jakewharton
butterknife
7.0.1

2.AndroidStudio中添加:
or Gradle:
compile ‘com.jakewharton:butterknife:7.0.1’

使用:
在你的application或者activity的onCreate中注册:

ButterKnife.bind(this);

1.使用@Bind()给xml中的view绑定,等同于findViewById

class ExampleActivity extends Activity { @Bind(R.id.title) TextView title; @Bind(R.id.subtitle) TextView subtitle; @Bind(R.id.footer) TextView footer; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.simple_activity); ButterKnife.bind(this); // TODO Use fields... }}

等同于这样书写:

public void bind(ExampleActivity activity) { activity.subtitle = (android.widget.TextView) activity.findViewById(2130968578); activity.footer = (android.widget.TextView) activity.findViewById(2130968579); activity.title = (android.widget.TextView) activity.findViewById(2130968577);}

要注意一点,通过@Bind绑定的控件不能声明为private和static

2.RESOURCE BINDING字符串颜色值values文件下一些xml的绑定

class ExampleActivity extends Activity { @BindString(R.string.title) String title; @BindDrawable(R.drawable.graphic) Drawable graphic; @BindColor(R.color.red) int red; // int or ColorStateList field @BindDimen(R.dimen.spacer) Float spacer; // int (for pixel size) or float (for exact value) field // ...}

3.NON-ACTIVITY BINDING fragment中的使用

public class FancyFragment extends Fragment { @Bind(R.id.button1) Button button1; @Bind(R.id.button2) Button button2; @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; }}

只要你在一开始使用了ButterKnife.bind(this);注册了之后,在该类中的任何地方都可以用到,比如自定义的adapter:

public class MyAdapter extends BaseAdapter { @Override public View getView(int position, View view, ViewGroup parent) { ViewHolder holder; if (view != null) { holder = (ViewHolder) view.getTag(); } else { view = inflater.inflate(R.layout.whatever, parent, false); holder = new ViewHolder(view); view.setTag(holder); } holder.name.setText("John Doe"); // etc... return view; } static class ViewHolder { //在这里 @Bind(R.id.title) TextView name; @Bind(R.id.job_title) TextView jobTitle; public ViewHolder(View view) { ButterKnife.bind(this, view); } }}

具体可以查看官网如下描述:

*Calls to ButterKnife.bind can be made anywhere you would otherwise put findViewById calls.Other provided binding APIs:1.Bind arbitrary objects using an activity as the view root. If you use a pattern like MVC you can bind the controller using its activity with ButterKnife.bind(this, activity).2.Bind a view's children into fields using ButterKnife.bind(this). If you use <merge> tags in a layout and inflate in a custom view constructor you can call this immediately after. Alternatively, custom view types inflated from XML can use it in the onFinishInflate() callback.*

4.多个view的使用 View List

@Bind({ R.id.first_name, R.id.middle_name, R.id.last_name })List<EditText> nameViews;The apply method allows you to act on all the views in a list at once.ButterKnife.apply(nameViews, DISABLE);ButterKnife.apply(nameViews, ENABLED, false);Action and Setter interfaces allow specifying simple behavior.static final ButterKnife.Action<View> DISABLE = new ButterKnife.Action<View>() { @Override public void apply(View view, int index) { view.setEnabled(false); }};static final ButterKnife.Setter<View, Boolean> ENABLED = new ButterKnife.Setter<View, Boolean>() { @Override public void set(View view, Boolean value, int index) { view.setEnabled(value); }};

An Android Property can also be used with the apply method.一个android属性也可以使用apply方法来绑定:

ButterKnife.apply(nameViews, View.ALPHA, 0.0f);

5.LISTENER BINDING监听器的绑定

  • 通过设置和控件相同名字的方法,监听器会被自动寻找到这个方法
@OnClick(R.id.submit)public void submit() { // TODO submit data to server...}

注意:这两句代码要写在一块,不要将上半部分写到声明控件的地方。

  • 通过view来寻找方法
@OnClick(R.id.submit)public void submit(View view) { // TODO submit data to server...}

如果上面的view是一个button,就可以写成这样

@OnClick(R.id.submit)public void sayHi(Button button) { button.setText("Hello!");}
  • 多个控件绑定同一个事件的处理
@OnClick({ R.id.door1, R.id.door2, R.id.door3 })public void pickDoor(DoorView door) { if (door.hasPrizeBehind()) { Toast.makeText(this, "You win!", LENGTH_SHORT).show(); } else { Toast.makeText(this, "Try again", LENGTH_SHORT).show(); }}
  • 自定义的views不需要指定ID来绑定他们自己的监听器
public class FancyButton extends Button { @OnClick public void onClick() { // TODO do something! }}

6.BINDING RESET
Fragments have a different view lifecycle than activities. When binding a fragment in onCreateView, set the views to null in onDestroyView. Butter Knife has an unbind method to do this automatically.
由于fragment的生命周期和activity不一样 ,所以需要做下处理:

public class FancyFragment extends Fragment { @Bind(R.id.button1) Button button1; @Bind(R.id.button2) Button button2; @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; } @Override public void onDestroyView() { super.onDestroyView(); //主要是这句话 ButterKnife.unbind(this); }}

7.OPTIONAL BINDINGS选择性注解
默认情况下,@Bind和listener的注入都是必须的,如果target view没有被发现,则会报错.
为了抑制这种行为,可以用@Nullable绑定来标记field和方法,让注入变成选择性的,如果targetView存在,则注入, 不存在,则什么事情都不做.
当布局被复用时,这个@Nullable绑定很有用.

@Nullable @Bind(R.id.might_not_be_there) TextView mightNotBeThere;@Nullable @OnClick(R.id.maybe_missing) void onMaybeMissingClicked() { // TODO ...}

8.MULTI-METHOD LISTENERS多方法的listener
有一些View的listener是有多个回调方法的,比如Spinner的onItemSelectedListener:

mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { } @Override public void onNothingSelected(AdapterView<?> parent) { }});

方法注解可以用来绑定到这些方法中的任何一个.
每一个注解有一个默认的callback,指定它绑定到什么方法上;可以通过callback参数指定为一个特定的方法
没有指定callback,默认对应onItemSelected()方法

@OnItemSelected(R.id.list_view)void onItemSelected(int position) { // TODO ...}//通过callback参数指定为一个特定的方法@OnItemSelected(value = R.id.maybe_missing, callback = NOTHING_SELECTED)void onNothingSelected() { // TODO ...}

9.BONUS
ButterKnife.findById()可以用来获取Activity,Dialog或View中的任何View

View view = LayoutInflater.from(context).inflate(R.layout.thing, null);TextView firstName = ButterKnife.findById(view, R.id.first_name);TextView lastName = ButterKnife.findById(view, R.id.last_name);ImageView photo = ButterKnife.findById(view, R.id.photo);Add a static import for ButterKnife.findById and enjoy even more fun.

ButterKnife自动完成了类型转换,所以获取出来以后不用进行显式强转,直接赋值给具体的View类型引用即可


分享给朋友:
您可能感兴趣的文章:
随机阅读: