在Kotlin的语言环境下使用ButterKnife框架
2015-11-05 15:14
501 查看
在学习Kotlin开发Android应用的过程中,势必要配合很多Android的开源框架一起使用,而ButterKnife是其中可能会经常用到的一个框架。
但是如果在Kotlin中直接使用ButterKnife的注解方式的话,会出现空指针的异常,导致绑定失败。
那么要如何才能在Kotlin的环境中使用ButterKinfe呢?
不要慌,ButterKnife的作者已经帮我们想好解决方案了,那就是——KotterKnife,多好,见名知意。
KotterKinife的GitHub地址是:https://github.com/JakeWharton/kotterknife
这个插件是建立在ButterKnife7的基础上的
也就是说 你在使用过程中,必须先将
写入项目Module的gradle配置文件中。
然后在项目的gradle配置文件中加入
然后我们看看不加KotterKnife的写法和普通的Kottlin的Android写法的区别:
使用前
使用后
OK,至此,我们可以继续在Kotlin中使用ButterKnife框架啦!
爽不?
但是如果在Kotlin中直接使用ButterKnife的注解方式的话,会出现空指针的异常,导致绑定失败。
那么要如何才能在Kotlin的环境中使用ButterKinfe呢?
不要慌,ButterKnife的作者已经帮我们想好解决方案了,那就是——KotterKnife,多好,见名知意。
KotterKinife的GitHub地址是:https://github.com/JakeWharton/kotterknife
这个插件是建立在ButterKnife7的基础上的
也就是说 你在使用过程中,必须先将
compile 'com.jakewharton:butterknife:7.0.1'
写入项目Module的gradle配置文件中。
然后在项目的gradle配置文件中加入
dependencies {
// (略)
compile 'com.jakewharton:kotterknife:0.1.0-SNAPSHOT'
}
repositories {
// (略)
maven {
url 'https://oss.sonatype.org/content/repositories/snapshots/'
}
}
然后我们看看不加KotterKnife的写法和普通的Kottlin的Android写法的区别:
使用前
public class MainActivity : Activity() {
var nameEditText: EditText? = null
var submitButton: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
nameEditText = findViewById(R.id.name_edit_text) as EditText
submitButton = findViewById(R.id.submit_button) as Button
submitButton!!.setOnClickListener {
val name = nameEditText?.getText().toString()
Toast.makeText(this, name, Toast.LENGTH_SHORT).show()
}
}
}
使用后
class MainActivity : Activity() {
val nameEditText: EditText by bindView(R.id.name_edit_text)
val submitButton: Button by bindView(R.id.submit_button)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
submitButton.setOnClickListener {
val name = nameEditText.getText().toString()
Toast.makeText(this, name, Toast.LENGTH_SHORT).show()
}
}
}
OK,至此,我们可以继续在Kotlin中使用ButterKnife框架啦!
爽不?
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- Android IPC进程间通讯机制
- Android Manifest 用法
- [转载]Activity中ConfigChanges属性的用法
- Android之获取手机上的图片和视频缩略图thumbnails
- Android之使用Http协议实现文件上传功能
- Android学习笔记(二九):嵌入浏览器
- android string.xml文件中的整型和string型代替
- i-jetty环境搭配与编译
- android之定时器AlarmManager
- android wifi 无线调试
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- android 代码实现控件之间的间距
- android FragmentPagerAdapter的“标准”配置
- Android"解决"onTouch和onClick的冲突问题
- android:installLocation简析
- android searchView的关闭事件
- SourceProvider.getJniDirectories