Kotlin 实现点击事件
上一篇文章写了hello word 与配置相关的信息,所有呢为了学习方便又开始写kotlin的点击事件。
1.点击弹出Toast 弹窗先上代码
这是activity_main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"/>
</RelativeLayout>
然后实现点击事件
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var te = findViewById(R.id.tv_test) as TextView;
te.text = "Hello word!"
te.textSize = 26.0f
te.setOnClickListener {
Toast.makeText(this,"Hello word!", Toast.LENGTH_SHORT).show()
}
}
}直接用空间.
setOnClickListener来监听点击事件,然后调用Android API中的Toast类来做弹窗具体Toast类是用来做什么的就需要自己去研究咯。
2.点击跳转activity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var te = findViewById(R.id.tv_test) as TextView;
te.text = "Hello word!"
te.textSize = 26.0f
te.setOnClickListener {
// Toast.makeText(this, "Hello word!", Toast.LENGTH_SHORT).show()
val intent = Intent()
//获取intent对象
intent.setClass(this, MainActivity1::class.java)
// 获取class是使用::反射
startActivity(intent)
}
}
}还是调用Android API。