【问题标题】:Unable to Instantiate fragment (Could not find fragment constructor)无法实例化片段(找不到片段构造函数)
【发布时间】:2019-03-12 11:03:04
【问题描述】:

我在某些设备上遇到了这个问题,并且在我的崩溃分析中遇到了错误。 当应用程序出现 ANR 问题并且错误是

时,就会出现此问题

无法启动活动 ComponentInfo{com.qwykr.dryver.base/com.qwykr.dryver.base.activities.MainActivity}:android.support.v4.app.Fragment$InstantiationException:无法实例化片段 com.qwykr。 dryver.base.fragments.SlideFragment:找不到片段构造函数

@Override
protected void onCreate(Bundle arg0) {
    // TODO Auto-generated method stub
    super.onCreate(arg0);
}

Slide 构造函数是

  @SuppressLint("ValidFragment")
public SideMenuFragment(Context mContext) {
    this.mContext=mContext;
}

有时 ANR 会导致此问题。 有时它工作正常,有时它会导致问题

【问题讨论】:

  • 那次崩溃不是 ANR。所有片段都需要一个public 零参数构造函数。您的崩溃是说 SlideFragment 没有 public 零参数构造函数。请注意,您的代码用于不同的类 (SideMenuFragment)。
  • @CommonsWare 我已经在所有构造函数中声明为 public。特别是 SlideFargment 有一个公共构造函数。
  • 它必须是public 零参数 构造函数。根据崩溃,你缺少这样的构造函数。
  • @CommonsWare 我是新手,面临同样的问题。你能解释一下我到底想在哪里创建构造函数以及如何创建?
  • @CommonsWare 你想创建两个构造函数,一个是默认的,一个是自定义的

标签: android android-fragments android-fragmentactivity


【解决方案1】:

这个例子在 Kotlin 上,但你也可以用 Java 来做

abstract class BaseFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }

    override fun onResume() {
        super.onResume()
    }
}
class ApproveFragment : BaseFragment() {

    companion object {
        fun newInstance(orderId: Int) = ApproveFragment().apply {
            arguments = Bundle(1).apply {
                putInt("ORDER_ID", orderId)
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater?,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater?.inflate(R.layout.fragment_approve, container, false)
    }

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
    }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多