相关疑难解决方法(0)

如何在 Android 中通过 ViewModel 类在 Activity 和 Fragment 之间共享数据?

我想知道是否可以传递在 Activity 类中声明的 String 数据并将 String 数据传递给 ViewModel 类,然后将数据传递给 Fragment 类。

视图模型类

class TimeTableViewModel extends ViewModel {

private MutableLiveData<String> start_time_str = new MutableLiveData<>();

void send_StartTime(String start_Time){
    start_time_str.setValue(start_Time);
}

LiveData<String> get_StartTime(){
    return start_time_str;
}}
Run Code Online (Sandbox Code Playgroud)

在 ViewModel 类中,我MutableLiveData<String> start_time_str已经初始化为new MutableLiveData<>();

我想void send_StartTime(String start_Time)在 Activity 类中使用函数来设置参数的值String start_Time并调用start_time_strFragment 类。

活动课

@Override
public boolean onOptionsItemSelected(MenuItem item){
    switch (item.getItemId()){
        case android.R.id.home:
            finish();
            break;
        case R.id.add_schedule_save:
            String start_time_str = startTime.getText().toString();
            Intent intent_restart0 = new Intent(TimeTable_Add_New_Schedule.this, MainActivity.class);
            startActivity(intent_restart0);
            TimeTableViewModel …
Run Code Online (Sandbox Code Playgroud)

android mvvm viewmodel android-livedata mutablelivedata

3
推荐指数
2
解决办法
5544
查看次数