Let's say we have a common fragment.
public class CommonFragmentForAB extends Fragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getDataFromApi();
}
public abstract void getDataFromApi() {
}
protected void showDataFromApi(List<SomeDataType> list) {
// code for showing data to RecyclerView
}
}
Then I want to make specific subclassses of CommonFragmentForAB
to be instantiated later.
public class A extends CommonFragmentForAB {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void getDataFromApi() {
// my implementation of getting data from API
showDataFromApi(list);
}
}
public class B extends CommonFragmentForAB {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void getDataFromApi() {
// my implementation of getting data from API
showDataFromApi(list);
}
}
What if do this instead?
public interface MyPresenter implements Serializable {
List<MyData> getDataFromApi();
}
public class CommonFragmentForAB extends Fragment {
private MyPresenter presenter;
public static CommonFragmentForAB newInstance(MyPresenter presenter) {
Bundle args = new Bundle();
args.putSerializable("presenter", presenter);
CommonFragmentForAB f = new CommonFragmentForAB();
f.setArguments(args);
return f;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
presenter = args.getSerializable("presenter");
}
public View onCreateView(LayoutInflater i, ViewGroup c, Bundle s) {
showDataFromApi(presenter.getDataFromApi());
}
protected void showDataFromApi(List<SomeDataType> list) {
// code for showing data to RecyclerView
}
}
What's the recommended approach here? Is there any reason to use one and not the other? I tend to choose the second approach as it doesn't create many Fragment
subclasses, but I haven't seen other people use this as common approach.
Aucun commentaire:
Enregistrer un commentaire