Android mvvm的基本使用

1,viewMode 是view和model的的中间层,有生命周期,并且即使切换屏幕也不用destroy

2,liveData是用于存储viewModel数据的抽象类,他的子类是MutableLiveData,, 一般两者结合使用,

2,dataBinding 是把viewModel和ui结合的google推出的官方框架

eg:

build.gradle

dataBinding{
        enabled = true
    }
public class UserActivity extends Activity {
 
      {@literal @}Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.user_activity_layout);
          final UserModel viewModel =                    ViewModelProviders.of(this).get(UserModel.class);
          viewModel.userLiveData.observer(this, new Observer() {
             {@literal @}Override
              public void onChanged(@Nullable User data) {
                  // update ui.
              }
          });
          findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
              {@literal @}Override
              public void onClick(View v) {
                  viewModel.doAction();
              }
          });
      }
  }

 

public class UserModel extends ViewModel {
      private final MutableLiveData<User> userLiveData = new MutableLiveData<>();
 
      public LiveData<User> getUser() {
          return userLiveData;
      }
 
      public UserModel() {
          // trigger user load.
      }
 
      void doAction() {
          // depending on the action, do necessary business logic calls and update the
          // userLiveData.
      }
  }

 

public class MyFragment extends Fragment {
      public void onStart() {
          UserModel userModel = ViewModelProviders.of(getActivity()).get(UserModel.class);
      }
  }

    
        
    

    
        
           android:text="@{userModel.userLiveData}" // 单向数据
        

        
           android:text="@={userModel.userLiveData}" // 双向数据
        

        

        
    

你可能感兴趣的:(Android)