Activity四大组件之一
1.activity跳转方法
Intent(Context packageContext,Class<?>cls)startActivity(Intent intent)
2.传参方法
intent.putExtra(key,value)getIntent().getStringExtra(key)
主要代码:
mainActivity
package com.example.appimport android.content.Intentimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.TextViewclass MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)val text = findViewById<TextView>(R.id.text_content)text.setOnClickListener {// val intent = Intent(this,SecondActivity::class.java)// val bundle = Bundle()// bundle.putString(\"\",\"\")// intent.putExtra(\"ss\",bundle)// intent.putExtra(\"name\", \"联动\")// intent.putExtra(\"age\",\"30\")// startActivity(intent)Intent(this,SecondActivity::class.java).apply {// putExtra(\"name\", \"aaa\")// putExtra(\"age\", \"30\")putExtra(\"user\",User())startActivity(this)}}}}
secondActivity
package com.example.appimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.TextViewimport kotlinx.android.synthetic.main.activity_second.*class SecondActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_second)//val text1 = findViewById<TextView>(R.id.tv_content)//val name = intent.extras?.getString(\"name\")// val name = intent.getStringExtra(\"name\")// tv_content.text = name// tv_age.text = intent.getIntExtra(\"age\",0 ).toString()val user = intent.getSerializableExtra(\"user\") as Usertv_content.text = user.nametv_age.text = user.age.toString()}}
User
package com.example.appimport android.os.Parcelimport android.os.Parcelableimport java.io.Serializableclass User() : Parcelable {var name:String? = \"神雕\"var age:Int = 18constructor(parcel: Parcel) : this() {name = parcel.readString()age = parcel.readInt()}override fun writeToParcel(parcel: Parcel, flags: Int) {parcel.writeString(name)parcel.writeInt(age)}override fun describeContents(): Int {return 0}companion object CREATOR : Parcelable.Creator<User> {override fun createFromParcel(parcel: Parcel): User {return User(parcel)}override fun newArray(size: Int): Array<User?> {return arrayOfNulls(size)}}}