簡體   English   中英

如何在課程和活動之間共享對象和變量

[英]how to share objects and variables among classes and activities

我需要與所有其他活動和類共享在第一個活動中創建的變量和對象(TextView,Button等)。

例如:

步驟1:在我的主要活動(A類)中,我調用了一個方法(在B類中),該方法可以動態創建多個按鈕。

步驟2:當用戶單擊這些按鈕之一時,我調用一種方法(在C類中),該方法檢查用戶是否“做了些什么”。

步驟3:如果用戶做了什么,我從C類中調用一個方法(在D類中),該方法將禁用我在B類中創建的所有按鈕。

問題:從D類訪問B類中創建的按鈕的正確方法是什么

我應該如何處理? 我甚至在不活動的簡單類中也必須使用此對象和變量,因此我無法使用Application。

這是根據您的解釋提出的建議。 請記住,我正在全心全意地打字,而且可能會有一些錯別字。

步驟1:在我的主要活動(A類)中,我調用了一個方法(在B類中),該方法可以動態創建多個按鈕。

public class A extends Activity implements OnClickListener{
      private ArrayList<Buttons> mybuttons = new ArrayList<Butons>

      // ... at some point you call B
      mybuttons.addAll(b.createButton(this));
           // createButtons should receive an OnClickListener as parameter to set on the buttons
           // createButtons returns a List<Buttons> that you add to your list.
           // note that it's NOT a static list, and that the list is part of the Activity, the Activity can hold reference to its views without problem

}

步驟2:當用戶單擊這些按鈕之一時,我調用一種方法(在C類中),該方法檢查用戶是否“做了些什么”。

步驟3:如果用戶做了什么,我從C類中調用一個方法(在D類中),該方法將禁用我在B類中創建的所有按鈕。

  // because A implements the OnClickListener, the OnClick is called inside A
  onClick(View v){
        // call the C to check. and make it return a boolean (true or false)
       if(c.CheckStuff()){
           // disable your buttons.
           for(Button btn:mybuttons) {  btn.setEnabled(false);  }
        }
  }

問題:從D類訪問B類中創建的按鈕的正確方法是什么

答案:公平地說,如果D僅禁用按鈕,則不必輸入我鍵入的那一行。 如果它正在做更多的工作,則可以將mybuttons傳遞給D,但我敦促不要在D內部保留對其的永久引用,這是因為D不在活動生命周期中。

暫無
暫無

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

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