In Kotlin,@Parcelize
Annotations are used to simplify implementation of AndroidParcelable
The process of interface.Parcelable
Interfaces are a way in Android for passing objects between components. Usually, implementParcelable
The interface requires a lot of boilerplate code to be written, but uses@Parcelize
Annotations can greatly simplify this process.
The following is used@Parcelize
Annotation steps and examples:
1. Add dependencies
First, make sure you add the necessary dependencies to your project. In yourTo the file, add the following plug-in:
apply plugin: 'kotlin-parcelize' // orplugins { id 'kotlin-parcelize' } // Notice!!!! kotlin-android-extensions Method is abandoned! Don't use it again!
2. Use @Parcelize annotation
Add on your Kotlin data class@Parcelize
Annotation and implementationParcelable
interface. Examples are as follows:
import import @Parcelize data class User( val id: Int, val name: String, val email: String ) : Parcelable
3. Enable the Parcelize function
existEnable the Parcelize function in the file:
android { ... kotlinOptions { jvmTarget = '1.8' } }
Sample code analysis
In the example above:
-
@Parcelize
Annotations are used to instruct the compiler to generate the requiredParcelable
accomplish. -
data class User
It is a data class with three attributes:id
、name
andemail
。 -
User
The class has been implementedParcelable
Interface, this is through@Parcelize
Annotations are automatically completed.
Using Parcelable objects
When you need to pass this in the IntentUser
When using an object, you can do this:
Passing objects
val user = User(1, "John Doe", "@") val intent = Intent(this, AnotherActivity::) ("user_key", user) startActivity(intent)
Receive object
val user = <User>("user_key")
This way, you can easily pass complex objects between different Android components such as Activity and Fragment without having to write them manuallyParcelable
Implement code.
Things to note
- use
@Parcelize
When , make sure that all attribute types support Parcelable or serialization. - Check your Kotlin version,
@Parcelize
Has been moved to the newer Kotlin versionPack it, not the old one
Bag.
Through these steps, you can use@Parcelize
Simplified annotationParcelable
The implementation greatly reduces the workload of manually writing boilerplate code.
This is the article about kotlin annotation @Parcelize used. This is all about this article. For more related kotlin annotations @Parcelize content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!