butterknife

2016-07-21  本文已影响41人  ykissbobo

配置

buildscript {
    dependencies {
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    }
}
apply plugin: 'com.neenbedankt.android-apt'
compile 'com.jakewharton:butterknife:8.2.1'
apt 'com.jakewharton:butterknife-compiler:8.2.1'

初始化

ButterKnife.bind(this);

在activity,setContentView,方法后设置.

fragment

Fragment的和adapter里也可以用,不过调用时要多加一个root view参数。
Fragegment使用时记得同时继承onDestroyView,并在其中将ButterKnife.reset

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

  @Override void onDestroyView() {
    super.onDestroyView();
    ButterKnife.reset(this);
  }

ButterKnife in Adapter ViewHolder

@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.person_item_layout, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        Person person = getItem(position);
        if (null != person) {
            holder.name.setText(person.getName());
            holder.age.setText(String.valueOf(person.getAge()));
            holder.location.setText(person.getLocation());
            holder.work.setText(person.getWork());
        }
 
        return convertView;
    }
 
    static class ViewHolder {
        @InjectView(R.id.person_name)
        TextView name;
        @InjectView(R.id.person_age)
        TextView age;
        @InjectView(R.id.person_location)
        TextView location;
        @InjectView(R.id.person_work)
        TextView work;
 
        public ViewHolder(View view) {
            ButterKnife.inject(this, view);
        }
    }

androidStudio插件:ButterKnife Zelezny

相关链接:http://blog.csdn.net/liang5630/article/details/46366901

ykissbobo
上一篇下一篇

猜你喜欢

热点阅读