Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I declare a Pair array using Kotlin

Tags:

android

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())
like image 927
André Silva Avatar asked Sep 29 '19 12:09

André Silva


2 Answers

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)
like image 189
AliSh Avatar answered Oct 11 '22 12:10

AliSh


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())
         }
like image 42
Patrick Nwafor Avatar answered Oct 11 '22 12:10

Patrick Nwafor