Android-Kotlin-Activity直接的跳转
程序员文章站
2022-04-01 18:41:17
1.选中应用包名packageName,右键:2.选中Kotlin:3.创建Kotlin的Activity完成:第一个Activity,MainActivitypackage cn.kotlinimport android.content.Intentimport android.support.v7.app.AppCompatActivityimport android.os.Bundleimport android.util.Logimport android.view.V...
1.选中应用包名packageName,右键:
2.选中Kotlin:
3.创建Kotlin的Activity完成:
第一个Activity,MainActivity
package cn.kotlin
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
class MainActivity : AppCompatActivity() {
// 定义tab变量为String类型的,注意:此String是Kotlin的
var tag:String = "MainActivity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// setContentView(R.layout.activity_main)
Log.d("@@@", "${tag}--onCreate()")
}
override fun onStart() {
super.onStart()
Log.d("@@@", "${tag}--onStart()")
}
override fun onResume() {
super.onResume()
Log.d("@@@", "${tag}--onResume()")
Thread(){
kotlin.run {
Thread.sleep(5000)
runOnUiThread(Runnable {
run {
startNextActivity()
}
})
}
}.start()
}
override fun onPause() {
super.onPause()
Log.d("@@@", "${tag}--onPause()")
}
override fun onStop() {
super.onStop()
Log.d("@@@", "${tag}--onStop()")
}
override fun onDestroy() {
super.onDestroy()
Log.d("@@@", "${tag}--onDestroy()")
}
/**
* 跳转第二个Activity
*/
fun startNextActivity() {
var intent:Intent = Intent()
intent.setClass(this@MainActivity, Main2Activity::class.java)
startActivity(intent)
}
/**
* 跳转第二个Activity
*/
fun startNextActivity(v: View) {
var intent:Intent = Intent()
intent.setClass(this@MainActivity, Main2Activity::class.java)
startActivity(intent)
}
}
第二个Activity,Main2Activity:
package cn.kotlin
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Toast
class Main2Activity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// setContentView(R.layout.activity_main2)
}
override fun onResume() {
super.onResume()
Toast.makeText(this@Main2Activity, "第二个Activity", Toast.LENGTH_LONG).show()
}
fun back(view: View) {
finish()
}
}
以上Activity总结:
-
1.所有的Activity周期方法,都是使用 override fun 方法() {} 方式写的;
-
2.定义变量 var tag:String = “MainActivity”
-
3.此线程是使用Kotlin的,所有没有new:
Thread(){
kotlin.run {
Thread.sleep(5000)
runOnUiThread(Runnable {
run {
startNextActivity()
}
})
}
}.start()
4.在Kotlin的Activity或组件,this使用方式是:this@MainActivity
5.Activity的跳转:this@MainActivity, Main2Activity::class.java
var intent:Intent = Intent()
intent.setClass(this@MainActivity, Main2Activity::class.java)
本文地址:https://blog.csdn.net/Androiddddd/article/details/108175009