当前位置:网站首页>First experience of ViewModel

First experience of ViewModel

2022-07-04 14:31:00 Novice Xiaowang

ViewModel The aim is to Life cycle Store and manage user interface related data in a conscious way , It can be used to manage Activity and Fragment Data in . It can also be handled Fragment And Fragment And so on .

Basic use  

1. Import dependence

implementation "androidx.lifecycle:lifecycle-extensions:2.2.0"

2. Create a solid object

public class User implements Serializable {
    String name;
    int age;

    public User(String name,int age){
        this.name = name;
        this.age = age;
    }
}

3. establish userModel Data model

public class UserModel extends ViewModel {
    public MutableLiveData<User> mLiveData = new MutableLiveData<>();

    public UserModel(){
        // Initial value 
        mLiveData.postValue(new User("wang",20));
    }

    // update operation 
    public void doSomething(){
        User user = mLiveData.getValue();
        user.name = " Reset data ";
        mLiveData.setValue(user);
    }
}

4.activity quote

        UserModel userModel = ViewModelProviders.of(this).get(UserModel.class);
        userModel.mLiveData.observe(this, new Observer<User>() {
            @Override
            public void onChanged(User user) {
                mMain2Binding.name.setText(user.name);
            }
        });
 public void onClick(View view) {
        switch (view.getId()) {
            case R.id.updateUser:
                userModel.doSomething();
                Log.e("tag","onclick");
                break;
        }
    }

5. ViewModel Ingenious use

1: Activity And Fragment" signal communication "


With ViewModel,Activity And Fragment Can share one ViewModel, because Fragment Is attached to Activity Upper , In instantiation ViewModel When the Activity Pass in ViewModelProviders, It will give you a Activity Created ViewModel, This Fragment You can easily access the ViewModel Data in . stay Activity Revision in China userModel After the data , The Fragment You can get the updated data .

public class MyFragment extends Fragment {
     public void onStart() {
        // I got it here ViewModel example , In fact, yes. Activity Created in is an instance
         UserModel userModel = ViewModelProviders.of(getActivity()).get(UserModel.class);
     }
 }


2: Fragment And Fragment" signal communication "


Let's take an example (Google The official example )

public class SharedViewModel extends ViewModel {
    private final MutableLiveData<Item> selected = new MutableLiveData<Item>();

    public void select(Item item) {
        selected.setValue(item);
    }

    public LiveData<Item> getSelected() {
        return selected;
    }
}


public class MasterFragment extends Fragment {
    private SharedViewModel model;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
        itemSelector.setOnClickListener(item -> {
            model.select(item);
        });
    }
}

public class DetailFragment extends Fragment {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedViewModel model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
        model.getSelected().observe(this, { item ->
           // Update the UI.
        });
    }
}

So let's define a ViewModel, Put some data in it , And then in MasterFragment and DetailFragment You can get this ViewModel, Got the ViewModel You can get the data in it , Equivalent to indirectly through ViewModel The communication

原网站

版权声明
本文为[Novice Xiaowang]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/185/202207041140542446.html