2013-10-29 80 views
7

我有一個Activity和非Activity類。如何從非活性類調用活動類中的方法如何調用非活動類的活動方法

public class MainActivity extends Activity { 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main2); 

     DataClass dc = new DataClass(); 
     dc.show();     
    } 

    public void call(ArrayList<String> arr) { 
     // Some code... 
    } 
} 

public class DataClass { 

    public void show(ArrayList<String> array) { 
     // Here I want to send this ArrayList values into the call 
     // method in activity class. 

     MainActivity act = new MainActivity(); 
     act.call(array);     
    } 
} 
+0

見也使用它http://stackoverflow.com/questions/19666572/how-to-call-a-method-in-another-activity-from-activity和http: //stackoverflow.com/questions/16653867/android-call-method-from-an-other-activity – RenniePet

回答

6

那麼有一些事情可以做。我認爲最簡單的你會在Context送入DataClass像這樣:

DataClass dc =new DataClass(); 
dc.show(this); 

而在你DataClass保存上下文爲全局變量Context context。然後像這樣使用它:

((MainActivity)context).call(array); 
13

只需在DateClass中創建一個回調接口。

public DateClass { 
    public interface IDateCallback { 
     void call(ArrayList<String> arr); 
    } 

    private IDateCallback callerActivity; 

    public DateClass(Activity activity) { 
     callerActivity = (IDateCallback)activity; 
    } 
... 
} 

public void show(ArrayList<String> array) {    
    callerActivity.Call(array); 
    ... 
} 

//And implements it inside your activity. 

public class MainActivity extends Activity 
     implements IDateCallback { 

    public void call(ArrayList<String> arr) { 

    } 
} 
+0

這是最好的方式來做到這一點,很明顯... – 2Dee

+0

感謝很多人你救了我的一天:) –

+0

是的我認爲這應該是最好的辦法。 但是有關這種方法的問題,因爲我們將一個活動引用傳遞給DateClass,它不會導致內存泄漏,因爲該活動將無法進行垃圾回收,因爲DateClass持有對它的引用? – akshayt23

1
((MainActivity)getContext).array(); 
0

只是要像一個單身:

TeacherDashboardSingleton:

public class TeacherDashboardSingleton { 
public Teacher_Dashboard aa; 
private static final TeacherDashboardSingleton ourInstance = new TeacherDashboardSingleton(); 
    public static TeacherDashboardSingleton getInstance() { 
     return ourInstance; 
    } 
} 

myActivity類:

onCreate(....){ 
.... 
    TeacherDashboardSingleton.getInstance().aa = this; 
.... 
} 

這將創建相同的實例的對象作爲活動

現在你可以從任何地方

相關問題