使用dataBinding、ViewModel和LiveData时的初始化

 Activity中:

public class MainActivity extends AppCompatActivity {

    ActivityMainBinding mBinding;
    MainActivityViewModel viewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this,R.layout.activity_main);
        viewModel = new ViewModelProvider(this).get(MainActivityViewModel.class);
        mBinding.setVm(viewModel);
        mBinding.setLifecycleOwner(this);
    }
}

注意要在xml文件中有资源名字才有设置资源的方法

我设置资源名字是vm,才会有setVm这个方法



    
          //ViewModel全类名
    

   .......

Fragment中:

public class TestFragment extends Fragment {

    TestFragmentLayoutBinding mbinding;
    TestViewModel viewModel;

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container, 
                    Bundle savedInstanceState) {
        mbinding = DataBindingUtil.inflate(inflater,                         
                      R.layout.test_fragment_layout,container,false);
        viewModel = new ViewModelProvider(getActivity()).get(TestViewModel.class);
        mbinding.setVm(viewModel);
        mbinding.setLifecycleOwner(getViewLifecycleOwner());
        return mbinding.getRoot();
    }
}

Activity和Fragment初始化dataBinding时都要设置资源(我定义的是vm)和LifecycleOwner

你可能感兴趣的:(android,java,android-studio)