【问题标题】:How to get Context for ClusterManager in Kotlin如何在 Kotlin 中获取 ClusterManager 的上下文
【发布时间】:2019-09-17 06:06:14
【问题描述】:

我可以使用哪个 Context 在 Kotlin Android 中初始化 ClusterManager?

var clusterManager: ClusterManager<MarkerCluster>? = null
clusterManager = ClusterManager(context, map);

【问题讨论】:

    标签: android android-fragments kotlin android-activity android-context


    【解决方案1】:

    我可以使用哪个 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-13
      • 2015-01-01
      • 2015-12-30
      相关资源
      最近更新 更多