I Have Separate Class I want to put inject in its body, but it's not allowed to make it A EntryPoint Because it's not a Fragment or Activity so Injection must be in Fragment or Activity
so Injection must be in Fragment or Activity
This is incorrect, Injection can be done anywhere as long as the EntryPoint
whether it was a Fragment or Activity is annotated with @AndroidEntryPoint
.
For example, If you have Class A that is a member of the MainActivity, and ClassB that is a dependency of Class A. So as long as MainActivity
is annotated with @AndroidEntryPoint
you can Inject ClassA into MainActivity and ClassB into ClassA.
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@Inject
lateinit var classA: ClassA
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
classA.test()
}
}
class ClassA @Inject constructor(){
@Inject
lateinit var classB: ClassB
fun test() = classB.test()
}
class ClassB @Inject constructor(){
fun test() = println("Hello World")
}
Output : Hello World
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.