Mar*_*ark 2 android builder-pattern android-fragments
我总是使用newInstance()模式创建片段并将我的参数传递给片段.这适用于一个或两个参数.我现在正在创建一个包含大约10个参数的片段,并且所有这些参数都是可选的.
我正在考虑使用Builder模式,类似于AlertDialog的工作方式.但是,我不确定实现它的最佳方法是什么,或者它是否是一个好主意.
这是我在思考的一个例子,但有更多的变量.
public class MyFragment extends Fragment {
private String name;
private static class Builder {
private String name;
public Builder setName(String name) {
this.name = name;
return this;
}
public MyFragment build() {
return new MyFragment(this);
}
}
// NOT ALLOWED
public MyFragment(Builder builder) {
name = builder.name;
}
// Rest of the fragment...
}
Run Code Online (Sandbox Code Playgroud)
这个问题是片段必须有一个默认的构造函数,所以这不起作用.
有没有"正确"的方法来实现这一目标?
在你Builder的build(),你可以这样做:
public MyFragment build() {
MyFragment fragment = new MyFragment();
Bundle bundle = new Bundle();
bundle.put(ARG_1_TAG, this.arg1);
...
fragment.setArguments(bundle);
return fragment;
}
Run Code Online (Sandbox Code Playgroud)
这样做的好处是可以为您的实例提供参数集,但不需要额外的newInstance()方法.
| 归档时间: |
|
| 查看次数: |
3308 次 |
| 最近记录: |