我想在java类中创建一个工厂方法,然后在活动中调用该方法以加载多个片段。
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.Men: {
FirstFragment firstfragment = new FirstFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, firstfragment);
transaction.commit();
break;
case R.id.Men: {
SecondFragment secondfragment = new SecondFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, secondfragment);
transaction.commit();
break;
}
}
答案 0 :(得分:2)
静态工厂方法,您可以简单地将所有内容分段保存,而无需公开。任何需要使用此片段的人都会清楚知道它需要什么,也不需要知道什么是密钥。只需发送所需的参数就足够了。
class FragmentFoo extends Fragment{
private static final String KEY_NAME = "name";
private String name;
public static Fragment newInstance(String name){
Bundle bundle = new Bundle();
bundle.putString(KEY_NAME, "name");
Fragment fragment = new FragmentFoo();
fragment.setArgs(bundle);
return fragment;
}
}