我在Android中使用Scala,我想将scala.collection.mutable.ArrayBuffer转换为Java.util.List。但它没有成功,有人可以帮助我吗?
代码:
package com.ssj.DoubanPipi.activity.fragment
import android.app.Fragment
import android.view.{View, LayoutInflater, ViewGroup}
import android.os.Bundle
import com.ssj.DoubanPipi.R
import android.widget.{ListView, SimpleAdapter}
import scala.collection.mutable.ArrayBuffer
import scala.collection.JavaConversions._
/**
* Created by shenshijun on 14-5-31.
*/
class MainFragment extends Fragment {
override def onCreateView(inflater: LayoutInflater, container: ViewGroup, savedInstanceState: Bundle) = {
val rootView = inflater.inflate(R.layout.main_fragment, container, false)
val listView = (rootView findViewById R.id.fragment_list).asInstanceOf[ListView]
val adapter = new SimpleAdapter(getActivity, MainFragment.menu_list,
R.layout.main_fragment_list, Array("text", "image"), Array(R.id.action, R.id.action_image))
listView setAdapter adapter
rootView
}
def onSign(view: View) {
}
}
object MainFragment {
val menu_list_text = Array(R.string.login, R.string.exit)
val menu_list_image = Array(R.drawable.douban, R.drawable.exit)
val menu_list = new ArrayBuffer[Map[String, Any]]()
val len = menu_list_image.length
for (index <- 0 until len) {
val map = Map("text" -> menu_list_text(index), "image" -> menu_list_image(index))
menu_list += map
}
}
,错误消息如下:
type mismatch;
found : scala.collection.mutable.ArrayBuffer[scala.collection.immutable.Map[String,Any]]
required: java.util.List[_ <: java.util.Map[String, _]]
val adapter = new SimpleAdapter(getActivity, MainFragment.menu_list,
^
答案 0 :(得分:1)
在menu_list上调用.toList()可以完成这项工作。
MainFragment.menu_list.toList
编辑:
如果您还需要将scala Map转换为java.util.Map,则此代码段应该有效:
menu_list.map(_。asInstanceOf [java.util.Map [String,Any]])
val javaMenuList: java.util.List[java.util.Map[String, Any]] = menu_list.map { map =>
val javaMap: java.util.Map[String, Any] = map
javaMap
}