我的應用程序包含三個類:主Activity,View_A,View_B。如何從Android類訪問其他類方法?
View_B需要訪問View_A的非靜態方法。怎麼做 ?
View_A和View_B都已在onCreate方法的主要活動中初始化。
謝謝。
我的應用程序包含三個類:主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