【问题标题】:KOTLIN -> InstantiationException: Unable to instantiate fragment make sure class name exists, is public, and has an empty constructor that is publicKOTLIN -> InstantiationException:无法实例化片段确保类名存在,是公共的,并且有一个公共的空构造函数
【发布时间】:2018-04-13 09:51:35
【问题描述】:

我在我的 android 应用中使用 kotlin 并收到了这个崩溃报告:

android.support.v4.app.Fragment$InstantiationException: Unable to instantiate fragment DetailsFragment: make sure class name exists, is public, and has an empty constructor that is public.

这是我的 DetailsFragment 类。

class DetailsFragment() : Fragment() {

private var workflowId: String? = null
private var workflowData: WorkflowData? = null
private var releaseAtStr: String? = null

public fun init(workflowId: String,
                workflowData: WorkflowData,
                releaseAtStr: String? = null) {
    this.workflowId = workflowId
    this.workflowData = workflowData
    this.releaseAtStr = releaseAtStr
}

private var context: BaseActivity? = null

override fun onAttach(context: Context?) {
    super.onAttach(context)
    if (context is BaseActivity?) {
        this.context = context
    }
}

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) =
        inflater?.inflate(R.layout.fragment_approval_details, container, false)

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)
    loadingOverlay?.show()
    populateWorkflowHistory()
}

}

知道如何修复它或至少重现它吗?

谢谢。

【问题讨论】:

    标签: android android-fragments kotlin kotlin-android-extensions


    【解决方案1】:

    尽量不要在片段中调用构造函数:

    class DetailsFragment : Fragment() {
    
    private var workflowId: String? = null
    private var workflowData: WorkflowData? = null
    private var releaseAtStr: String? = null
    
    public fun init(workflowId: String,
                    workflowData: WorkflowData,
                    releaseAtStr: String? = null) {
        this.workflowId = workflowId
        this.workflowData = workflowData
        this.releaseAtStr = releaseAtStr
    }
    

    【讨论】:

    • 这是什么意思?我很新。你能解释一下吗?
    • 我刚刚从 DetailsFragment 之后删除了 ( ) :)
    • 这是构造函数
    • 这意味着会调用 Fragment 的构造函数,对吗?但是如果我left(),功能是一样的,只是DetailsFragment构造函数调用Fragment构造函数...
    • 这里有一个解释为什么stackoverflow.com/questions/10450348/…你不应该覆盖片段中的构造函数。如果您没有为您的片段声明构造函数,则会为您创建一个默认的空构造函数以满足异常中所述的要求
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-28
    相关资源
    最近更新 更多