如何从Android类访问其他类方法?
我的应用程序包含三个类:主Activity,View_A,View_B。如何从Android类访问其他类方法?
View_B需要访问View_A的非静态方法。怎么做 ?
View_A和View_B都已在onCreate方法的主要活动中初始化。
谢谢。
您可以将View_A作为公共实例变量存储在主活动中。然后将主要活动的上下文传递给View_B。然后,您可以通过View_B中主要活动的上下文访问View_A的实例。
这里基本上我的意思
这是你的主要活动:
Context context;
public View_A viewA;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
viewA = new View_A();
View_B viewB = new View_B(context);
}
它会使用一个getter方法从场景中获得viewA可能会更好。
这里是View_B例子类:
class View_B {
Context activityContext;
// constructor
View_B (Context _c)
{
activityContext = _c;
viewA = activityContext.viewA;
}
}
,基本上是我的意思,但正如我在我的评论说,TEDS解决方案似乎更优雅。
我想他的意思更多的东西是这样的:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = this;
View_A viewA = new View_A();
View_B viewB = new View_B();
// create a setter method in viewB class to set viewA instance into it after viewA & viewB are created. or i guess you could pass viewA to viewB in the constructor of viewB
viewb.setViewA(viewA);
}
我希望从东西可以帮你
基本上,你需要在View_B里面引用View_A。一种方法是在View_B中定义一个可供Activity类访问的View_A变量。在onCreate中,只要创建了View_A和View_B,就将该变量设置为View_A的实例。
ahh这是比我更有效的方式,因为它没有将上下文传递给View_B – wired00 2011-04-18 03:17:56
这是siple.You JST需要创造需求类的在你当前的参考类并使用referenceedObject.methodName()调用方法;
任何代码示例?谢谢。 – user403015 2011-04-18 04:48:18
查看我的更新。我已经包括了我的意思,但我喜欢Teds解决方案更优雅 – wired00 2011-04-18 05:11:44