kotlin中,兩個頁面進行跳轉,用parcelable值傳遞,常常會遇到傳遞過程中值獲取不到的問題。存在此問題的原因,可能包括以下幾點:
1.服務器傳值爲空或者爲空對象;
2.定義在kotlin中的對象所包含的字段沒有進行判空處理;
3.parcelable在傳遞多屬性對象時,傳值失效問題(可能是parcelable的一個坑);
那怎麼解決呢:
1.用@Parcelize註解的形式,對parcelable值進行轉化;
2.對結構對象,進行可null處理,防止服務器返回值不規範,造成值獲取不到的問題.
當然如果一個對象中,包含列表數據的情況:
比如
class subApplyBean():Parcelable{
var agentName:String?=null
var id:Int?=null
......
var customList: ArrayList<CustomBean>? = null
}
這個時候需要對customList進行手動轉化,因爲Kotlin現在只支持對常規屬性字段的自動轉化;
Step1:在constructor中 list進行如下添加
constructor(parcel:Parcel):this(){
......
customList=parcel.readArraylist(........) as ArrayList<CustomBean>?
}
Step2:在SubApplyBean.write(parcel:Parcel,flags:Int)方法中,加入
SubApplyBean.write(parcel:Parcel,flags:Int){
......
parcel.writeList(customList)
}
好了,大功告成!! 到這裏,以上操作在kotlin中,基本上能解決用parcelable傳值失效的問題。