1. 实现一个类
:类名()
2. 简单实现textView设置文字、给imageView设置图片、给button设置监听,直接根据id进行操作,无需findViewById
demo_title.text = "我是一个标题"
intro_image.setImageResource(R.mipmap.radio_yes)
demo_button.setOnClickListener {
Toast.makeText(this, "我是一个button", Toast.LENGTH_LONG).show()
}
3. 定义方法
无返回值无参private fun showInfo() {
Log.e("kotlin==", "定义一个无返回值无参数的方法")
}
有返回值有参数
private fun getInfo(number: Int): String {
return "返回一个有参数的数据 $number"
}
4. 创建接口
interface KotlinInter { fun logInfo(info: String): String }
5. 继承类并实现接口(类后面跟括号,接口直接写名称)
KotlinDemo : Activity(), KotlinInter
6. 使用Intent实现跳转
var intent = Intent(KotlinDemo@ this, KotlinSecond::class.java)
startActivity(intent)
7. 工具类,定义静态方法
class KotlinTools {
companion object {
fun dp2px(context: Context, number: Float): Float {
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, number, context.resources.displayMetrics)
}
}
}
8. 回调java与kotlin对比
JAVA: call.enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call, Response<String> response) { } @Override public void onFailure(Call<String> call, Throwable throwable) { } });
KOTLIN:
call.enqueue(object : Callback<String> { override fun onResponse(call: Call<String>, response: Response<String>) { } override fun onFailure(call: Call<String>, throwable: Throwable) { } })