CompoundView中的ViewModel引用(自定义视图)

时间:2017-12-29 16:55:46

标签: android mvvm android-architecture-components android-viewmodel

我正在使用MVVMAndroid Architecture Components库跟踪Data Binding架构。

TL; DR

在复合视图中引用ViewModel对象是否违反了MVVM架构?我查看了Google的示例,并且只看到它在Activity / Fragment XML中使用,但不在自定义视图中使用。

有问题的代码

我有一个复合视图,我想在很多地方重复使用。它从XML实例化。此视图将从用户输入填充。我想确保用户输入的任何内容都会在方向更改后幸存下来。请仔细考虑我编写的以下代码来说明该场景:

public class RestaurantActivity extends AppCompatActivity {

    RestaurantViewModel viewModel;

    RestaurantActivityBinding binding;

    @Override
    public void onCreate( Bundle savedInstanceState ) {
        super.onCreate( savedInstanceState );

        binding = DataBindingUtil.setContentView(this, R.layout.restaurant_activity );

        viewModel = ViewModelProviders.of( this ).get( RestaurantViewModel.class );

        //is this "legal" for MVVM
        binding.selectionView.setRestaurantViewModel( viewModel );

        viewModel.extraHotSause.observe ( this, new Observer() {

          @Override
          void onChange(Boolean extraHotSauce ) {
               binding.selectionView.extraHotSauce( extraHotSauce );
          }

        });
    }
}

查看型号:

public class RestaurantViewModel extends android.arch.lifecycle.ViewModel {
    public MutableLiveData<Boolean> extraHotSauce = new MutableLiveData<>();
}

餐厅选择视图:

public class RestaurantSelectionView extends ConstraintLayout {

    private RestaurantSelectionViewBinding binding;

    private RestaurantViewModel viewModel;
    ...

    private void init() {            
        binding = RestaurantSelectionViewBinding.inflate(...);
    }

    public void onExtraHotSauceSelection( boolean yesPlease ) {
          viewModel.extraHotSauce.setValue( yesPlease );
    }

    @Override
    public void onDetachedFromWindow() {
          viewModel = null;
          super.onDetachedFromWindow();
    }
}

0 个答案:

没有答案