黄油刀是JakeWharton开源的一款Android视图字段方法绑定快速注解框架。可以不用findById,setOnclick等。大大提高开发效率。
依赖
compile 'com.jakewharton:butterknife:10.1.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.1.0'
Butterknife基本使用
在Activity中绑定
public class MainActivity extends AppCompatActivity {
@BindView(R.id.btn1) Button button1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
}
在fragment中绑定
public class BlankFragment extends Fragment {
private BlankViewModel mViewModel;
public static BlankFragment newInstance() {
return new BlankFragment();
}
private Unbinder unbinder;
@BindView(R.id.txt1)
TextView textView;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.blank_fragment, container, false);
unbinder = ButterKnife.bind(this,root); //绑定视图
return root;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewModel = new ViewModelProvider(this).get(BlankViewModel.class);
}
@Override
public void onDestroy() {
super.onDestroy();
unbinder.unbind(); //视图销毁需解绑
}
}
Butterknife具体使用
单个组件id绑定:
@BindView(R.id.txt1)
TextView textView;
点击事件:
@OnClick(R.id.btn1)
public void btn1(){
}
多组件同一点击事件
@OnClick({R.id.btn2,R.id.btn3,R.id.btn4})
public void btn2(View view){
}
}
多组件多点击事件
@OnClick({R.id.btn2,R.id.btn3,R.id.btn4})
public void btn2(View view){
switch (view.getId()){
case R.id.btn2:
Toast.makeText(MainActivity.this,"btn2",Toast.LENGTH_SHORT).show();
break;
case R.id.btn3:
Toast.makeText(MainActivity.this,"btn3",Toast.LENGTH_SHORT).show();
break;
case R.id.btn4:
Toast.makeText(MainActivity.this,"btn4",Toast.LENGTH_SHORT).show();
break;
}
}
列表组件的item点击事件
@OnItemClick({R.id.listView})
public void test(int position){
Toast.makeText(MainActivity.this,"position:"+position,Toast.LENGTH_SHORT).show();
}
网友评论