Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

android - How to compile class which extends my fragment

In kotlin I have two fragments - first fragment and second fragment, which extends first fragment. But during compiling of my app I have an error:

FragmentAllTags.kt: (9, 20): Primary constructor call expected.

Please, help me fix this error for child class, to for constructor without params called constructor with empty list argument, and if I will call constructor with param - variable get value of param from constructor, i.e as it works in parent class.

Parent class:

open class FragmentAllCategories(var categories: MutableList<ModelCategory>) : Fragment() {
constructor(): this(mutableListOf<ModelCategory>()) {
}
…
}

child class:

class FragmentAllTags(categories: MutableList<ModelCategory>): FragmentAllCategories(categories) {
    constructor(): super() {

    }
…
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you have a primary constructor, the secondary constructors cannot call super constructors. They have to call the primary constructor.

A Fragment's primary constructor should always be empty, because the framework can destroy and recreate it, and it recreates it by calling the empty constructor. Therefore, your FragmentAllCategories code would not be able to rely on the categories collection having the items you first passed to it. So if you instantiate your Fragment with some Categories and start it, if the screen rotates or the app goes to the background and comes back, those ModelCategories will be gone.

To avoid this problem, you can put the categories collection in an Activity-scoped ViewModel, which will survive screen rotations and app-backgrounding. Or you can make your ModelCategory a Parcelable and add it to the Fragment's bundle before you first start it. The bundle will automatically be restored when the Fragment is recreated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...