ViewModel.设置数据



我有两个片段。在第一个卡片中。当您单击卡时,第二片片段将使用完整的描述打开。我放入了安装在适配器中的捆绑标签。在第二片片段中,我得到它,我需要通过标签设置数据。

在Onchanged方法中,我编写model.setverse((list)数据);但是什么都没有发生。

首先,我尝试做tvtitle.setText(data.gettitle),但也没有发生任何事情。

ViewModel

 public class DataViewModel extends AndroidViewModel {
LiveData<Data> currentVerse;
public DataViewModel(@NonNull Application application, final int verseId) {
    super(application);
    int verseId1 = verseId;
    DataRepository repository = new DataRepository(application);
    currentVerse = repository.getById(verseId);
}
public LiveData<Data> getById() {
    return currentVerse;
}
public void setVerse(List<Data> data) {
    this.currentVerse= (LiveData<Data>) data;
}

public static class ModelFactory extends ViewModelProvider.NewInstanceFactory {
    @NonNull
    private final Application application;
    private final int verseId;
    private final DataRepository repository;
    public ModelFactory(@NonNull Application application, int id) {
        super();
        this.application = application;
        this.verseId = id;
        repository = new DataRepository(application);
    }

    @NonNull
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
        if (modelClass == DataViewModel.class) {
            return (T) new DataViewModel(application, verseId);
        }
        return null;
    }
}

}

片段

 public class DataFragment extends Fragment {
private int verseId;
private static final String KEY_VERSE_ID = "KEY_VERSE_ID";
public TextView tvTitle;
public DataFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootViewRead = inflater.inflate(R.layout.fragment_data, container, 
false);
    Toolbar toolbar = rootViewRead.findViewById(R.id.toolbar);
    AppCompatActivity activity = (AppCompatActivity) getActivity();
    if (activity != null) {
        activity.setSupportActionBar(toolbar);
    }
    setHasOptionsMenu(true);
    tvTitle = (TextView) rootViewRead.findViewById(R.id.text);
    DataViewModel.ModelFactory factory = new DataViewModel.ModelFactory(
            getActivity().getApplication(), 
 getArguments().getInt(KEY_VERSE_ID));
    final DataViewModel model = ViewModelProviders.of(this, factory)
            .get(DataViewModel.class);
    model.getById().observe(this, new Observer<Data>() {
        @Override
        public void onChanged(Data data) {
            model.setVerse((List<Data>) data);

        }
    });
    return rootViewRead;
}
public static DataFragment forData(int verseId) {
    DataFragment fragment = new DataFragment();
    Bundle args = new Bundle();
    args.putInt(KEY_VERSE_ID, verseId);
    fragment.setArguments(args);
    return fragment;
}

如有必要,我将添加DAO和存储库类

以下是您需要修改以设置livedata的值的部分:

LiveData<<List>Data>> currentVerse;
public void setVerse(List<Data> data) {
    this.currentVerse.setValue(data);
}

有关更多详细信息,请单击此处

相关内容

  • 没有找到相关文章

最新更新