butterknife的使用

butterknife

讓咱們從繁瑣的 findViewById 中解救出來。下面直接是使用方法java

Activityeclipse

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

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


      adapterthis

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

    還能夠綁定多控件idspa

@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 銷燬

默認狀況下  and  找到控件都是不容許爲空的,不然會拋異常。
能夠添加  容許爲空code

 ButterKnife.reset(this);@InjectView@OnClick@Optional
@Optional @InjectView(R.id.might_not_be_there) TextView mightNotBeThere;

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

butterknife 在eclipse裏面的配置:orm


點ok便可!server

相關文章
相關標籤/搜索