简体   繁体   中英

How can I declare a Pair array using Kotlin

I want to do something like this: (the code is in java)

Pair[] pairs = new Pair[1];

I want to convert this code to kotlin, the problem is I don't know how to initialize this array. This is the code I have:

val prof_intent = Intent(this, NewObjectiveActivity::class.java)
    val pairs = arrayOf(1)
    pairs[0] = Pair<View, String>(fabNewObjective, "activity_trans")

    val options = ActivityOptions.makeSceneTransitionAnimation(this, pairs)
    startActivity(prof_intent, options.toBundle())

First Solution:

You can define an array list of pairs as you had in your java code in this way:

val pairList = ArrayList<Pair<String, Int>>()

Then you can define your variable and add it to your list:

val pair = Pair("hi", 12)
pairList.add(pair)

Second Solution:

var pairs = arrayOf(Pair("hi", 12), Pair("bye", 13))

Third Solution:

pairs = arrayOf("hi" to 12, "bye" to 13)

Just pass the pairs in the method indicating each pairs with their index number.

The method makeSceneTransitionAnimation(Activity activity, Pair<View, String>... sharedElements) in the ActivityOptions class requires an activity as the first parameter and could have as many pairs as possible as the following parameter.

See the code below for a better understanding:

val pair = listOf<Pair<View, String>>(
             Pair<View, String>(img, "image_shared"),
             Pair<View, String>(txtview, "text_shared"),
             Pair<View, String>(imgView, "image_view_shared")
         )

         val options: ActivityOptions = ActivityOptions.makeSceneTransitionAnimation(this, pair[0], pair[1], pair[2])
         Intent(this, SharedElementActivity::class.java).also {
             startActivity(it, options.toBundle())
         }

According to Google Documents , it's better to do like this:

// Rename the Pair class from the Android framework to avoid a name clash
import android.util.Pair as UtilPair
...
val options = ActivityOptions.makeSceneTransitionAnimation(this,
        UtilPair.create(view1, "agreedName1"),
        UtilPair.create(view2, "agreedName2"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM