简体   繁体   中英

TextView from SecondActivity become visible after a button from MainActivity is pressed?

I'm very new to Android Studio Development and I was wondering how to do this, when I click a button on MainActivity, it will direct me to secondActivity where the text become visible (Originally TextView will not be visible until the button from MainActivity is pressed)

imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                String status = "Success!";
                intent2.putExtra("Status",status);
                startActivity(intent);
             }
        });

I want to make an if-else statement for this (on SecondActivity page) where if user straight away go to SecondActivity, it will not display any text there. But if pressed the button on MainAcitivty page, the system will go to SecondActivity with the TextView displayed.

Thanks!

Basically, there are several approaches you can do that.

  1. Use intents pass data Sure you pass a boolean type or whatever you want into this intent, I think this is the approach you are trying to make here. So I can give you an example: In your first activity you can do something like this,
button.setOnClickListener {
    val intent = Intent(this@MainActivity, SecondActivity::class.java).apply {
        val status = true
        putExtra("Status", status)
    }
    startActivity(intent)
}

And in your second activity, in your need to override onCreate to parse your intents to decide your text want to display or not.

val status = intent.extras?.getBoolean("Status")
if(status) {
  hideText()
} else {
  showText()
}
  1. the other approach you can deal with it is try to create singleton class to keep the status in this class, and based this singleton class status, you may choose to hide/show your text. However this solution isn't the recommended way to do it. Because global state is bad for testing and just pollute the code.

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