class Music(var musicID:Int?=null,var musicTitle: String? = null) : Serializable{}
MainACclass MainActivity : AppCompatActivity() { overrIDe fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentVIEw(R.layout.activity_main) var music=Music(1, "回梦游仙") val intent = Intent(this@MainActivity, JumpActivity::class.java) intent.putExtra("musicbean", music) startActivity(intent) }}
JumpACclass JumpActivity : AppCompatActivity() { val TAG="JumpActivity" overrIDe fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentVIEw(R.layout.activity_jump) var music=intent.getSerializableExtra("musicbean") as Music? if (music != null) { music.musicTitle?.let { Log.e(TAG, it) } } }}
三:Parcelable方式(方式二)代码量大但效率高1.建立列继承Parcelable接口实现两个方法,提供一个CREATOR 常量实际上把原Serializable接口给去掉改为Parcelable接口,然后导入就行字符串型数据就调用writeString() 方法, 整型数据就调用writeInt() 方法, 以此类推class MusicParce(var musicID:Int?=null,var musicTitle: String? = null) : Parcelable { constructor(parcel: Parcel) : this( parcel.readValue(Int::class.java.classLoader) as? Int, parcel.readString() ) { } overrIDe fun writetoParcel(parcel: Parcel, flags: Int) { parcel.writeValue(musicID) parcel.writeString(musicTitle) } overrIDe fun describeContents(): Int { return 0 } companion object CREATOR : Parcelable.Creator<MusicParce> { overrIDe fun createFromParcel(parcel: Parcel): MusicParce { return MusicParce(parcel) } overrIDe fun newArray(size: Int): Array<MusicParce?> { return arrayOfNulls(size) } }}
2.实例化并传递参数class MainActivity : AppCompatActivity() { overrIDe fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentVIEw(R.layout.activity_main) //var music=Music(1, "回梦游仙") var musicpl=MusicParce(1, "桃花岛 ") val intent = Intent(this@MainActivity, JumpActivity::class.java) intent.putExtra("musicbean", musicpl) startActivity(intent) }}
3. get方式变化class JumpActivity : AppCompatActivity() { val TAG="JumpActivity" overrIDe fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentVIEw(R.layout.activity_jump) var music=intent.getParcelableExtra("musicbean") as MusicParce? if (music != null) { music.musicTitle?.let { Log.e(TAG, it) } } }}
四:使用Bundle原理就将多个东西打包,先封在Bundle,再将其用intent传递 //使用Bundle val bundle = Bundle() val intent = Intent(this@MainActivity, JumpActivity::class.java) //设置数据 //设置数据 val ID = 3 val musicTitle = "夏鱼" //把数据保存到Bundle里 //把数据保存到Bundle里 bundle.putInt("musicID", ID) bundle.putString("musicTitle", musicTitle) //把bundle放入intent里 //把bundle放入intent里 intent.putExtra("Message", bundle) startActivity(intent)
取出来 val bundle = intent.getBundleExtra("Message") //获取数据 //获取数据 val ID = bundle!!.getInt("musicID") val musicTitle = bundle!!.getString("musicTitle") Log.e(TAG, "${ID}+${musicTitle}")
1. 序列化此处引用若put时未加 标识且只有一个Bundle,get时也可以不加。以上是内存溢出为你收集整理的【Android-Kotlin】Intent-序列化-Bundle全部内容,希望文章能够帮你解决【Android-Kotlin】Intent-序列化-Bundle所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)