Android开发自用笔记之Activity

  • Post author:
  • Post category:其他




Activity四大组件之一

1.activity跳转方法

Intent(Context packageContext,Class<?>cls)
startActivity(Intent intent)

2.传参方法

intent.putExtra(key,value)
getIntent().getStringExtra(key)

主要代码:

mainActivity

package com.example.app

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView

class 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.app

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import 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 User
        tv_content.text = user.name
        tv_age.text = user.age.toString()
    }
}

User

package com.example.app

import android.os.Parcel
import android.os.Parcelable
import java.io.Serializable

class User() : Parcelable {
    var name:String? = "神雕"
    var age:Int = 18

    constructor(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)
        }
    }
}



版权声明:本文为weixin_46473347原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。