我可以使用哪个 Context 在 Kotlin Android 中初始化 ClusterManager?
这取决于你在哪里使用clusterManager = ClusterManager(context, map);
例如,如果您在任何活动中使用它,请像这样使用
clusterManager = ClusterManager(this, map);
// or
clusterManager = ClusterManager(this@LoginActivity, map);
例如,如果您在任何片段中使用它,请像这样使用
class FragmentOne : Fragment() {
var mContext: Context? = null
override fun onAttach(context: Context) {
super.onAttach(context)
mContext = context
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val rootView = inflater.inflate(R.layout.fragment_one, container, false)
clusterManager = ClusterManager(mContext, map)
return rootView
}
}
注意
您可以使用getActivity() 和getContext() 在片段中获取context
但是getActivity() 可以返回null 所以我建议你应该使用onAttach() 在片段中获取context