如何将可变列表传递给捆绑包?

时间:2018-07-02 07:11:56

标签: android list kotlin bundle mutable

我想将可变列表添加到捆绑包中,但是似乎没有一种方法可以实现此目的。

var bundle = Bundle()
                bundle.put...????("LIST", fbModel.recipeArray)

您可以使用putString等,但是似乎没有putMutableList作为选项。该怎么办?

更新 忘了提到mutableList这个RecipeArray是一个object。像这样:

var recipeArray: MutableList<RecipeTemplate>

...其中RecipeTemplate是一个看起来像这样的类:

class RecipeTemplate {
    var recipeHeader: String? = null
    var recipeText: String? = null
    var recipeImage: String? = null
    var recipeKey: String? = null
}

更新 根据@EpicPandaForce的回答解决了问题:

gridView.setOnItemClickListener { parent, view, position, id ->
                Log.d("TAGA", "CLICKETICLICK " + position)
                Log.d("TAGA", "CLICKETICLICK " + fbModel.recipeArray[1].recipeHeader) //PASSES

                val intent = Intent(classContext, Recipes::class.java)

                var bundle = Bundle().apply {
                    putParcelableArrayList("LIST", ArrayList<Parcelable>(fbModel.recipeArray))
                    putInt("POSITION", position)
                }

                intent.putExtra("bundle", bundle)
                startActivity(intent)
            }

但是在其他活动中接收它仍然有问题。来自onCreate的代码:

var passedIntent = intent.extras
var bundle: Bundle = passedIntent.getBundle("bundle")
var counter: Int = bundle.getInt("POSITION", 0)
var recipeArray: ArrayList<Parcelable> = bundle.getParcelableArrayList("LIST")
var recipeList: MutableList<RecipeTemplate> = recipeArray as MutableList<RecipeTemplate>

Log.d("TAGA", "PASSED " + counter) //PASSES
if(recipeArray != null) {
    Log.d("TAGA", "HERE " + recipeArray[1].recipeHeader.toString()) //Null
    Log.d("TAGA", "HERE " + recipeList[1].recipeHeader.toString()) //Null
    Log.d("TAGA", "HERE " + recipeArray.size) //PASSES

}

通过counter并显示正确的数字。 recipeArray.size被传递并显示正确的数字。但是,其他日志recipeArray[1].recipeHeader.toString()recipeList[1].recipeHeader.toString()都为空,即使它们在放入束中之前包含正确的值。我需要做些什么...枚举...解析列表?还是我错过了什么?

3 个答案:

答案 0 :(得分:4)

你可以

apply plugin: 'kotlin-android-extensions' 

androidExtensions {
    experimental = true
}

然后

@Parcelize
class RecipeTemplate : Parcelable {
    var recipeHeader: String? = null
    var recipeText: String? = null
    var recipeImage: String? = null
    var recipeKey: String? = null
}

然后

var bundle = Bundle().apply {
                  putParcelableArrayList("LIST", ArrayList<Parcelable>(fbModel.recipeArray))
             }

答案 1 :(得分:1)

这取决于您列表中有哪些项目。 Bundle有几种方法可让您在其中放置列表,例如putIntegerArrayListputStringArrayList。如果需要使用自定义类型,可以将其设置为Parcelable,然后使用putParcelableArrayList

当然,所有这些方法如其名称所建议的都专门采用ArrayList实例,而不仅仅是任何MutableList。因此,您可以将所有MutableList的用法更改为使用ArrayList,也可以将其放入捆绑包中,从现有的ArrayList创建一个新的MutableList

bundle.putParcelableArrayList("key", ArrayList(myParcelableList))

答案 2 :(得分:0)

recipeArray的类型是什么?您可以放置​​各种ArrayList(而不是List!),包括Integers,CharSequences,Strings,以及最常见的Parcelables。有关完整API,请参见文档:https://developer.android.com/reference/android/os/Bundle