簡體   English   中英

按下 MainActivity 中的按鈕后,SecondActivity 中的 TextView 變得可見?

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

我對 Android Studio Development 非常陌生,我想知道如何做到這一點,當我單擊 MainActivity 上的一個按鈕時,它將引導我到 secondActivity 文本變得可見(最初 TextView 直到 MainActivity 的按鈕才可見按下)

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);
             }
        });

我想為此(在 SecondActivity 頁面上)做一個 if-else 語句,如果用戶直接將 go 轉到 SecondActivity,它將不會在那里顯示任何文本。 但是如果按下 MainAcitivty 頁面上的按鈕,系統將 go 到 SecondActivity 並顯示 TextView。

謝謝!

基本上,有幾種方法可以做到這一點。

  1. 使用意圖傳遞數據當然,您傳遞了 boolean 類型或您想要的任何內容,我認為這是您在這里嘗試采用的方法。 所以我可以給你舉個例子:在你的第一個活動中,你可以做這樣的事情,
button.setOnClickListener {
    val intent = Intent(this@MainActivity, SecondActivity::class.java).apply {
        val status = true
        putExtra("Status", status)
    }
    startActivity(intent)
}

在你的第二個活動中,你需要重寫onCreate來解析你的意圖來決定你的文本是否要顯示。

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. 但是,此解決方案不是推薦的方法。 因為全局 state 不利於測試,只會污染代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM