如何从Android类访问其他类方法?

| 我的应用程序包含三个类:主活动,View_A,View_B。 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);
} 
我希望从中可以得到一些帮助     
这很简单。您首先需要在当前类中创建需要类的引用,然后使用referencedObject.methodName()调用该方法。     
基本上,您需要在View_B中引用View_A。一种方法是在View_B中定义活动类可访问的View_A变量。在onCreate中,只需将变量设置为View_A的实例,即可同时创建View_A和View_B。     

要回复问题请先登录注册