butterknife的使用

butterknife

让我们从繁琐的 findViewById 中解救出来。下面直接是使用方法

Activity

class ExampleActivity extends Activity {
  @InjectView(R.id.title) TextView title;
  @InjectView(R.id.subtitle) TextView subtitle;
  @InjectView(R.id.footer) TextView footer;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_activity);
    ButterKnife.inject(this);
    // TODO Use "injected" views...
  }
}

Fragment  销毁的时候掉用  ButterKnife . reset ( this );

public class FancyFragment extends Fragment {
  @InjectView(R.id.button1) Button button1;
  @InjectView(R.id.button2) Button button2;

  @Override View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fancy_fragment, container, false);
    ButterKnife.inject(this, view);
    // TODO Use "injected" views...
    return view;
  }
}

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 {
    @InjectView(R.id.title) TextView name;
    @InjectView(R.id.job_title) TextView jobTitle;

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

VIEW LISTS
@InjectViews({ R.id.first_name, R.id.middle_name, R.id.last_name }) List<EditText> nameViews;


CLICK LISTENER INJECTION
@OnClick(R.id.submit)
 public void submit() {
   // TODO submit data to server...
 }

@OnClick(R.id.submit)
 public void sayHi(Button button) {
   button.setText("Hello!");
 }

还可以绑定多控件id

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


INJECTION RESET 销毁

ButterKnife.reset(this);



默认情况下 @InjectView and @OnClick 找到控件都是不允许为空的,否则会抛异常。

可以添加  @Optional  允许为空

 
@Optional @InjectView(R.id.might_not_be_there) TextView mightNotBeThere;

    @Optional @OnClick(R.id.maybe_missing) void onMaybeMissingClicked() {
    // TODO ...
    }


<span style="color: rgb(0, 128, 128);">butterknife 在eclipse里面的配置:</span>



ok !


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值