Android Kotlin环境使用ButterKnife
2018-03-28 本文已影响259人
进击的包籽
Butter Knife 黄油刀大家应该都挺熟悉的,有这个之后,就不用写一堆的findViewById,体力活,最近试着玩玩Kotlin语言,也就尝试在Kotlin语言环境下使用ButterKnife,有一点小问题,解决并分享一下。
先看看java环境的用法
-
安装插件,然后重启Android studio。
安装插件.jpg
2.使用,点击一下在setContentView(R.layout.activity_main);然后快捷键Alt+insert。

3.使用。

4.完成
@BindView(R.id.circleView)
CircleView circleView;
@BindView(R.id.tv_test)
TextView tvTest;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
/*
* 多个控件点击事件,会有大括号包起来,中间逗号隔开
* */
@OnClick({R.id.circleView, R.id.tv_test})
public void onViewClicked(View view)
{
switch (view.getId())
{
case R.id.circleView:
break;
case R.id.tv_test:
break;
}
}
@Override
protected void onDestroy()
{
ButterKnife.bind(this).unbind();
super.onDestroy();
}
Kotlin环境
1.随意新建一个kotlin文件

2.然后工程会有几个地方变化




3.添加对kotlin的支持
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
//控件插件
implementation 'com.jakewharton:butterknife:8.8.1'
kapt 'com.jakewharton:butterknife-compiler:8.8.1'
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
}

4.使用,直接用就好,不用再BindView了。


5.注意要对应的xml,以免同样的控件id引起空指针异常。
