While implementing Architecture components I am facing this issue
import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.LifecycleOwner
import android.os.Bundle
import com.reversebits.trendyvidz.R
class MainActivity : LifecycleOwner {
override fun getLifecycle(): Lifecycle {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.AppTheme) //This shows error
setContentView(R.layout.activity_main) //This shows error
init()
}
private fun init() {
when {
isNetworkAvailable() -> toast("Yes Avail")
else -> toast("No")
}
}
}
How do I suppose to get Activity context-based methods here like setContentView()
of AppCompatActivity?
As already pointed out, if you want to make an Activity you need to extend Activity.
Other than that there is a couple of issues in your code:
1)
If you use support library 26.1.0+ and lifecycles 1.0.0-alpha9-1+ lifecycles are already included because
2)
If you use older support libraries or lifecycles you had two options.
2a)
If your activity extended
FragmentActivity
, you would instead extendLifecycleActivity
and that's it.2b)
If you couldn't do that, you'd implement
LifecycleRegistryOwner
, for example:That's where sample codes end but I don't see any code actually dispatching the events. Upon investigating current
SupportActivity
it turns out it's usingReportFragment
to dispatch all events. Add this to properly dispatch events:Another thing, this is a mistake:
The method
onCreate
triggersON_CREATE
event. Not the other way around. You'll get stack overflow error like this.You use
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
annotation on methods, that you want to trigger automatically afteronCreate
is called, not ononCreate
method itself.