初始化ViewModelFactory

时间:2017-08-12 22:03:06

标签: java android dependency-injection android-architecture-components

根据我的理解,如果ViewModel类在其构造函数中包含参数,则ViewModelFactory类是必需的。除了使用依赖注入之外,我怎样才能在我的活动中初始化我的ViewModelFactory类?以下是我的工厂类

public class ViewModelFactory  implements ViewModelProvider.Factory {
private final Map<Class<? extends ViewModel>, Provider<ViewModel>> creators;


public ViewModelFactory(Map<Class<? extends ViewModel>, Provider<ViewModel>> creators) {
    this.creators = creators;
}

@SuppressWarnings("unchecked")
@Override
public <T extends ViewModel> T create(Class<T> modelClass) {
    Provider<? extends ViewModel> creator = creators.get(modelClass);
    if (creator == null) {
        for (Map.Entry<Class<? extends ViewModel>, Provider<ViewModel>> entry : creators.entrySet()) {
            if (modelClass.isAssignableFrom(entry.getKey())) {
                creator = entry.getValue();
                break;
            }
        }
    }
    if (creator == null) {
        throw new IllegalArgumentException("unknown model class " + modelClass);
    }
    try {
        return (T) creator.get();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
  } 
}

这是我的活动课

public class RestaurantListActivity extends AppCompatActivity implements LifecycleRegistryOwner {

private LifecycleRegistry lifecycleRegistry = new LifecycleRegistry(this);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_restaurant_list);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    //How do I initialize this?
    ViewModelFactory mViewModelFactory;

    MyViewModel viewModel = ViewModelProviders.of(this,mViewModelFactory).get(MyViewModel.class);
    viewModel.init();

    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

   }
}

1 个答案:

答案 0 :(得分:0)

你可以这样做:

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    ViewModelProvider.Factory factory = new ViewModelProvider.Factory() {
        @Override
        public <T extends ViewModel> T create(Class<T> modelClass) {
            if (modelClass.equals(SomeObject.class)) {
                // instantiate `someObject`
                return someObject;
            } else if (modelClass.equals(SomeOtherObject.class)) {
                // instantiate `someOtherObject`
                return someOtherObject;
            } else {
                return ...;
            }

        }
    }
}