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())
4

Best Answer


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())}

To give an example that's then used in an activity transition:

var pairs = arrayListOf<Pair<View,String>>()for (view in listOfViewsToBeTransitioned) {val transitionPair = Pair.create(view, view.id.toString())pairs.add(transitionPair)}val pairsArray:Array<Pair<View,String>> = pairs.toTypedArray()val transitionOptions = ActivityOptions.makeSceneTransitionAnimation(this, *(pairsArray))val intent = Intent(this, targetActivity::class.java)startActivity(intent, transitionOptions.toBundle())

The * splat operator expands a typed array into the varargs that makeSceneTransitionAnimation will accept. This example also assumes there is a meaningful value in view.id, I generally make this the resource identifier of the drawable used in the view.

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

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