9

我正在MVVM使用Android Architecture ComponentsData Binding图书馆关注体系结构。

TL;博士

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();
    }
}
4

0 回答 0