0

我需要与所有其他活动和类共享我在第一个活动中创建的变量和对象(TextView、按钮等)。

例如:

第 1 步:在我的主要活动(A 类)中,我调用了一个方法(在 B 类中),该方法在动态上创建了几个按钮。

第 2 步:当用户单击其中一个按钮时,我调用一个方法(在 C 类中)来检查用户是否“做了某事”。

第 3 步:如果用户做了某事,我从 C 类调用一个方法(在 D 类中),该方法禁用我在 B 类中创建的所有按钮。

问题:从 D 类到达 B 类中创建的按钮的正确方法是什么

我应该如何处理?即使在不是活动的简单类中,我也必须使用这个对象和变量,所以我不能使用 Application.

4

1 回答 1

0

这是根据您的解释提出的建议。请记住,我是用心输入的,可能有一些错别字。

第 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 不是活动生命周期的一部分。

于 2013-02-08T12:31:27.787 回答