简体   繁体   中英

Function onCreate not execute on activity start Kotlin Android

I'm new to Android development and I just started learning.

Here's my problem:

My onCreate function in activity_main works normally, it shows everything. Then he logs in and shows me the second activity and there also the onCreate function works but when I go to the third activity the onCreate function does not execute.

DashboardActivity.kt

class DashboardActivity : AppCompatActivity() {
    @SuppressLint("MissingInflatedId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_dashboard)
        val policy = ThreadPolicy.Builder().permitAll().build()
        StrictMode.setThreadPolicy(policy)
       sendGet()
       // sendPostRequest()
    }
fun openTest(view: View){
        setContentView(R.layout.activity_test);
    }
}

TestActivity.kt

class TestActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_test)
        println("test")
    }
}

Could someone guide me or explain what and how? I've been sitting on this for a while, searching the inte.net and nothing...

I searched the inte.net, tried solutions, tried to create more activities, turned on debug mode by adding breakpoint and it doesn't even enter this function

To start an Activity, you need to call the following:

startActivity(Intent(this, NextActivity::class.java))

Otherwise, onCreate(Bundle?) will not be called if you do not explicitly call the above.

So in your case, seems that you would like to get to TestActivity in openTest(View) , you should have something like this:

fun openTest(view: View) {
  startActivity(Intent(this, TestActivity::class.java))
  // Calling setContentView() will not trigger another Activity
  // setContentView(R.layout.activity_test);
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM