In my main activity I am having a method that I need to call from a secondary java class. I used the constructor of the secondary java class to receive reference to the main Activity. I then tried to use this reference to invoke that method from the body of the secondary java class. But java doesn't recognize that method through the passed reference?
My main Activity is as below:
public class MainActivity extends Activity{
public void onCreate(){
TestClass mTestClass = new TestClass(this);
}
public testMethod(){
// do some work here
}
}
now, in my TestClass.java I receive reference to the MainActivity:
public class TestClass{
public TestClass(Activity mActivity){
//Android开发者_开发知识库/Java doesn't recoginze testMethod here????
mActivity.testMethod();
}
}
I've been trying to solve this issue for a few days with no success. I urgently need your help and would appreciate any suggestion!
P.S. The TestClass will act as a library that everyone can call it from their android application. In other words, I provide the TestClass as the library. The user then implements the content of a method that will be executed whenver certain conditions are met. Thus, I need to call that specific method (which will be defined by the user in their own Activity) through a reference which is passed by the user to my library class
In your application:
public class MainActivity extends Activity implements Testeable {
public void onCreate(){
TestClass mTestClass = new TestClass(this);
}
public testMethod(){
// do some work here
}
}
In your library:
public interface Testeable {
public void testMethod();
}
public class TestClass{
public TestClass(Testeable mActivity){
//Android/Java doesn't recoginze testMethod here????
mActivity.testMethod();
}
}
If you pass the Activity class in the constructor of the TestClass the testMethod will not be visible because it is contained in your MainActivity class and not the Activity. So change
public TestClass(Activity mActivity){
...
to
public TestClass(MainActivity mActivity){
...
or cast mActivity or use an interface like Julio Gorgé suggested
精彩评论