[英]java-call a function in a class from another one
class A: A类:
public class A extends Activity{
B b;
@Override
public void onCreate(Bundle savedInstanceState) {
b.sample();
}
public void test(){
//Do Something
}
}
Class B: B级:
public class B{
public void sample(){
//Do Something
}
}
Its Ok To call methods Of Class B in the Class A, But How Is it Possible to Call Class A methods And Functions In Class B? 可以在A类中调用B类的方法,但是如何在B类中调用A类的方法和函数呢?
I cant create An New Object Of Class A in Class B like: 我无法在B类中创建A类的新对象,例如:
A a = new A();
because It then Creates A Whole New Activity (Am I Right?!) 因为它随后创建了一个全新的活动(我对吗?!)
Should I Use Interface to Achieve this? 我应该使用界面来实现这一目标吗?
define the B constructor and make it receive the activity 定义B构造函数并使其接收活动
public class B{
private Activity theActivityA;
B(Activity activitiy){
this.theActivityA = activitiy;
if(this.theActivityA!=null){
this.theActivityA.test();
}
}
Yes, you can use interfaces. 是的,您可以使用界面。 I assume that you need to notify the activity about something.
我假设您需要通知活动某些事情。
public class A extends Activity implements B.IListener {
....
public class B{
IListener mListener;
B(IListener listener){
mListener=listener;
}
public void sample(){
//Do Something
}
public interface IListener {
something();
}
}
So, in B you can call methods to any instance of IListener, not just A. 因此,在B中,您可以调用方法到IListener的任何实例,而不仅仅是A。
Hope it helps. 希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.