Reputation: 101
I am currently trying to make one of my classes implement Parcelable
but I can't do it properly. This is the class.
class T(val eyes:Int,val img:ImageButton){
var image = img
var value = eyes
var isPressed = false
}
Android Studio suggests that my constructor should look similar to this when implementing Parcelable
, but I don't know how to use a parcel to initialize my ImageButton
.
constructor(parcel: Parcel) : this(
parcel.readInt(),
//parcel.
) {
value = parcel.readInt()
isPressed = parcel.readByte() != 0.toByte()
}
Tried to use a parcel. any and cast it to an ImageButton
without success, any suggestions on how to solve this? Thanks in advance.
Upvotes: 1
Views: 755
Reputation: 110
If you want to make a class like this, you can create it in this way
class T(var eyes: Int, var img: ImageButton, var isPressed: Boolean = false)
ImageButton class doesn't implement the Parcelable
interface, in this case, you cannot pass it into Parcel. It's not a good approach to put Views into Parcel, you can save their state into primitives or classes which implements Parcelable
and restore it after that. For example, if you want to pass a text from EditText
to another activity, you can put this text into Parcel as String
, and restore it in the next Activity
.
Upvotes: 2
Reputation: 1369
If you are using kotlin always use data class for model. and use @Parcelize
annotation so you don't need to write extra boilerplate code. But in your case you can't Parcelize
ImageButton
it's not a class that implements Parcelable
interface
In case you are searching about a normal way to implement, Just use like that:
@Parcelize
data class UserInformationData(
var userId : String? = null,
var firstName : String? = null,
var lastName : String? = null,
var email : String? = null,
var gender : String? = null,
var dateOfBirth : String? = null,
var phoneNumber : String? = null
):Parcelable
Upvotes: 0