我想从类名 Core 创建一个新对象 public Core core = new Core();
并在其他类中共享它,这样每个类都可以进行更改,而无需再次创建对象。
示例:
public class Core {
protected int width = 3;
protected int hieght = 4;
protected int calc = 0;
public int calculate(){
calc = width * hieght;
return calc ;
}
}
FragmentA代码:
public class FragmentA extends Fragment {
public Core core = new Core();
public int resualt = core.calculate();
private RelativeLayout llLayout = null;
private FragmentActivity faActivity = null;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
faActivity = (FragmentActivity) super.getActivity();
System.out.println(" resualt: " + resualt);
return inflater.inflate(R.layout.fragment_a,container,false);
}
public Core getCore(){
return core;
}
public void doSomthing (){
core.width +=1;
core.hieght -=1;
core.calc *=2;
}
}
现在我想检索类中的对象:
public class FragmentC extends Fragment {
//public Core core = object => here I dont know How to continu?
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_c,container,false);
}
public void doSomthing (){
core.width +=2;
core.hieght -=1;
core.calc *=5;
}
}
我怎样才能做到这一点?
最佳答案
我认为这里的方法之一是使用 Singleton pattern ,因为您始终可以在应用程序的任何部分从中访问数据。在您的示例中,只需将 Core
类设为 Singleton,并始终使用 getInstance()
方法访问数据。
另一种方法是使用接口(interface)
和Bundle
将数据从Fragment
传递到Fragment
,您可以阅读有关此的更多信息 here .
关于java - 如何在多个类之间共享对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26703405/