黄油刀 butterKnife

黄油刀 butterKnife:
自动findViewByID(),自动添加点击事件onClick();
步骤:
1.引入依赖包 butterknife:8.4.0 jakewharton:butterknife:8.4.0
2.安装插件 Android ButterKnife Zelezny
3.配置build
1、工程的gradle文件增加android-apt插件的classpath
    dependencies {
	...

        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    }
2、模块的gradle文件头部,增加使用插件的声明:
	apply plugin: 'com.neenbedankt.android-apt'
3、模块gradle的依赖部分,增加依赖本身,及使用apt处理依赖脚本:
	compile 'com.jakewharton:butterknife:8.4.0'
	apt 'com.jakewharton:butterknife-compiler:8.4.0'
4.使用:
鼠标停在想要找控件的布局上,按Alt +Insert ,如图选择
Generate ButterKnife Injections 如下图:

勾选你想要添加点击事件的控件,点击Confirm确定。如下图:

就会生成如下标记的代码:


在listView中使用黄油刀:
在listView中使用黄油刀:
代码:
public class MyListAdapter extends BaseAdapter 
    Context mContext;
    LayoutInflater inflater;
    ViewHolder holder;
    public MyListAdapter(Context mContext) {
        this.mContext = mContext;
        inflater = LayoutInflater.from(mContext);
    }
    public int getCount() {
        return 40;
    }
    @Override
    public Object getItem(int position) {
        return null;
    }
    @Override
    public long getItemId(int position) {
        return 0;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.mylist_layout, parent, false);
            holder=new ViewHolder(convertView);
            convertView.setTag(holder);
        }else{
            holder= (ViewHolder) convertView.getTag();
        }
        return convertView;
    }
     class ViewHolder {
        @BindView(R.id.iv)
        ImageView iv;
        @BindView(R.id.tv1)
        TextView tv1;
        @BindView(R.id.tv2)
        TextView tv2;
        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}

public class MainActivity extends AppCompatActivity {

    MyListAdapter adapter;
    @BindView(R.id.lv)
    ListView lv;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        adapter=new MyListAdapter(this);
        lv.setAdapter(adapter);

    }

    @OnItemClick(R.id.lv)
    public void onItemClick( int position) {
        Toast.makeText(MainActivity.this, "这是第"+position+"个", Toast.LENGTH_SHORT).show();
    }

}



阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页