Varargs Kotlin Java interop not working properly

被刻印的时光 ゝ 提交于 2019-12-05 01:24:21

The answer is the * symbol before array variable:

import android.support.v4.util.Pair as AndroidPair

// ...    

val pair1 = AndroidPair<View, String>(fab, 
    getString(R.string.transition_fab))
val pair2 = AndroidPair<View, String>(findViewById(R.id.app_bar),
    getString(R.string.transition_appbar))

ActivityOptionsCompat.makeSceneTransitionAnimation(this@MyActivity,
    *arrayOf(pair1, pair2)).toBundle();

This worked for me:

import android.support.v4.util.Pair

// ...    

val options = ActivityOptionsCompat.makeSceneTransitionAnimation(activity,
        Pair<View, String>(image, image.transitionName),
        Pair<View, String>(title, title.transitionName))

startActivity(intent, options.toBundle())

It may be the case that you're accidentally using kotlin.Pair instead of android.util.Pair. Please add the following import directive to the beginning of your file:

import android.util.Pair

This is a whole code snippet I would recommend for :

companion object {
    const val EXTRA_ITEM = "EXTRA_ITEM"
    const val TRANSITION_NAME_IMAGE = "TRANSITION_NAME_IMAGE"
    const val TRANSITION_NAME_TEXT = "TRANSITION_NAME_TEXT"
  }

  override fun onItemClick(pos: Int, item: Item, imageView: ImageView, textView: TextView) {
    val intent = Intent(context, YourActivity::class.java)
    intent.putExtra(EXTRA_ITEM, item)
    intent.putExtra(
      TRANSITION_NAME_IMAGE,
      ViewCompat.getTransitionName(imageView)
    )
    intent.putExtra(
      TRANSITION_NAME_TEXT,
      ViewCompat.getTransitionName(textView)
    )

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
      val optionsCompat = ActivityOptionsCompat.makeSceneTransitionAnimation(
        context as Activity,
        androidx.core.util.Pair<View,String>(imageView, imageView.transitionName),
        androidx.core.util.Pair<View,String>(textView, textView.transitionName)
      )
      startActivity(intent, optionsCompat.toBundle())
    } else {
      startActivity(intent)
    }
  }

You have to also implement this method for transaction in your activity for back to Previous screen .

override fun onOptionsItemSelected(item: MenuItem): Boolean {
    val id = item.itemId
    if (id == android.R.id.home) {
      supportFinishAfterTransition()
      return true
    }
    return super.onOptionsItemSelected(item)
  }

The key is to initiate your Pair like this: Pair<View, String>(view, string) otherwise it complains.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!