我有三个片段类,每个片段都带有自己的自定义适配器
//Fragment class 1
static CusomtAdapter1 adapter1;
//Fragment class 2
static CusomtAdapter2 adapter2;
//Fagment class 3
static CusomtAdapter3 adapter3;
所有三个适配器都基于相同的基础数据。我想同时给所有人打电话notifyDataSetChanged()
。所以我将它们传递给另一个班级。
//Fragment class 1
UpdateAdapters updateAdapters = new UpdateAdapters(adapter1);
//Fragment class 2
UpdateAdapters updateAdapters = new UpdateAdapters(adapter2);
//Fagment class 3
UpdateAdapters updateAdapters = new UpdateAdapters(adapter3);
这是UpdateAdapters
类
public class UpdateAdapters {
private static CusomtAdapter1 adapter1;
private static CusomtAdapter2 adapter2;
private static CusomtAdapter3 adapter3;
//Public Constructors
public void UpdateAdapters(CusomtAdapter1 adapter1){
this.adapter1 = adapter1;
}
public void UpdateAdapters(CusomtAdapter2 adapter2){
this.adapter2 = adapter2;
}
public void UpdateAdapters(CusomtAdapter3 adapter3){
this.adapter3 = adapter3;
}
//Public methods
public static void update(){
adapter1.notifyDataSetChanged();
adapter2.notifyDataSetChanged();
adapter3.notifyDataSetChanged();
}
}
我可以像这样更新它们
UpdateAdapters.update()
我的问题是我无法将我的adpaters传递给我的更新类
//Fragment class 1
UpdateAdapters updateAdapters = new UpdateAdapters(adapter1); // error: UpdateAdapters() cannot be applied to come.example.myname.myapp.CusomtAdapter1
//Fragment class 2
UpdateAdapters updateAdapters = new UpdateAdapters(adapter2); // error: UpdateAdapters() cannot be applied to come.example.myname.myapp.CusomtAdapter2
//Fagment class 3
UpdateAdapters updateAdapters = new UpdateAdapters(adapter3); // error: UpdateAdapters() cannot be applied to come.example.myname.myapp.CusomtAdapter3
怎么回事?
由于
答案 0 :(得分:2)
作为@MikeM。指出,你的"建设者"基本上都是方法。因为它们不返回对象的实例,但它们返回void
。因此,要获得构造函数,您必须这样做:
public UpdateAdapters(...) { }
但是,您应该为所有片段创建一个单个实例,而不是每次设置适配器时都创建一个新实例。为此,您可以使用以下内容创建实例:
public class UpdateAdapters {
private static UpdateAdapters instance = null;
// constructor
protected UpdateAdapters() { }
// get the current instance
public static UpdateAdapters getInstance() {
if (instance == null) {
// create a new one if it doesn't exist
instance = new UpdateAdapters();
}
return instance;
}
...
}
在片段中,当您想要添加适配器时,您将获得此对象的当前实例(并且不会在每次创建新对象时创建)并将适配器设置为它。所以,你会打电话:
UpdateAdapters.getInstance().doSomething();
获取当前创建的对象并使用此对象的实例执行某些操作 你可以这样设置碎片'适配器。假设你在UpdateAdapters类中有这个:
public class UpdateAdapters {
...
private CusomtAdapter1 adapter1;
private CusomtAdapter2 adapter2;
private CusomtAdapter3 adapter3;
public void setAdapterOne(CusomtAdapter1 adapter1) {
this.adapter1 = adapter1;
}
public void setAdapterTwo(CusomtAdapter2 adapter2) {
this.adapter2 = adapter2;
}
public void setAdapterThree(CusomtAdapter3 adapter3) {
this.adapter3 = adapter3;
}
public void update() {
adapter1.notifyDataSetChanged();
adapter2.notifyDataSetChanged();
adapter3.notifyDataSetChanged();
}
}
然后,在每个片段中,您将使用以下命令添加其适配器:
UpdateAdapters.getInstance().setAdapterOne(adapter1); // same for each one
最后,用相同的东西更新它们:
UpdateAdapters.getInstance().update();