java黄油刀_github 黄油刀(注解) butterknife

butterknife

便捷开发

1、下载

Project->

dependencies {

...

classpath 'com.jakewharton:butterknife-gradle-plugin:8.5.1'

...

}

2、下载

App->

dependencies {

...

implementation 'com.jakewharton:butterknife:8.5.1'

annotationProcessor "com.jakewharton:butterknife-compiler:8.5.1"

...

}

3、使用

注意:这里的View不可以是private或static类型

1.代替findViewById()

TextView textView = (TextView) findViewById(R.id.text_view);

直接->

@BindView(R.id.text_view)

TextView mTextView;

然后在onCreate()的setContentView()下添加ButterKnife.bind(this);

Activity中:

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

ButterKnife.bind(this);

}

Fragment中:

View rootView = inflater.inflate(R.layout.frag_main, container, false);

ButterKnife.bind(this, rootView);//这里有些不同

Adapter中:

static class ViewHolder {

@BindView(R.id.text_view) TextView mTextView;

@BindView(R.id.button) Button mButton;;

public ViewHolder(View view) {

ButterKnife.bind(this, view); //这里有些不同

}

}

注意:在使用BindView方法的时候,如果目标View没有找的的话,会抛出异常。如果不想受到这个异常,可以使用@Nullable

2. 点击事件——@OnClick

@OnClick(R.id.button)

public void onButtonClick(View view) {

Toast.makeText(this, "button被点击了", Toast.LENGTH_SHORT).show();

}

多个点击事件:

@OnClick({R.id.text_view, R.id.button, R.id.edit_text})

public void onTextviewClick(View view) {

switch (view.getId()){

case R.id.text_view:

Toast.makeText(this, "text_view被点击了", Toast.LENGTH_SHORT).show();

break;

case R.id.button:

Toast.makeText(this, "button被点击了", Toast.LENGTH_SHORT).show();

break;

case R.id.edit_text:

Toast.makeText(this, "edit_text被点击了", Toast.LENGTH_SHORT).show();

break;

}

}

list点击:

@OnItemClick(R.id.list_view)

void onItemClick(int potion) {

Toast.makeText(getContext(), "点击了:" + potion, Toast.LENGTH_SHORT).show();

}

3.资源绑定

可以利用@BindBool,@BindColor,@BindDimen,@BindDrawable,@BindInt,@BindString来绑定资源

@BindString(R.string.title) String title;

@BindDrawable(R.drawable.graphic) Drawable graphic;

@BindColor(R.color.red) int red; // int or ColorStateList field

...

4、(可选)Zelezny插件自动生成..

https://www.jianshu.com/p/5dead31a84f6

更多再添加...

持续...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值