java - 使用视图模型将数据从活动发送到片段
问题描述
我正在尝试使用片段而不是启动活动在我的主要活动中显示我的数据。这是我的主要活动屏幕
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/colorBg"
tools:context=".ui.search.SearchActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/teamsRecyclerView"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/toolbar" />
<FrameLayout
android:id="@+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="130dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
在我的主要活动课程中,我有以下 private void goToFragmentClass(Watch watch) {
Gson gson = new Gson();
viewModel.getTeamById(thisTeam.getTeamId()).observe(this, new Observer<Team>() {
String json = "";
@Override
public void onChanged(Team team) {
if (team != null)
json = gson.toJson(team);
else
json = gson.toJson(thisTeam);
//intent.putExtra("Watch", json);
// startActivity(intent);
}
});
}
我的问题是如何开始在这里提交片段并将其传递json
给片段类,我知道如何使用 Activity 执行此操作,但我想改用片段。
我的视图模型类
public class SearchViewModel extends AndroidViewModel {
private MainRepository mainRepository;
public SearchViewModel(Application application) {
super(application);
mainRepository = new MainRepository(application);
}
LiveData<List<Team>> getTeamList(String teamName) {
return mainRepository.getTeamByName(teamName);
}
LiveData<Team> getTeamById(String id) {
return mainRepository.getTeam(id);
}
}
解决方案
您可以使用 Bundle 将数据从 Activity 发送到 Fragment。
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putString(KEY, json);
fragment.setArguments(bundle);
//Perform Fragment add/replace using fragment transaction here.
在你的片段中:
if (arguments != null)
String json = getArguments.getString(KEY, json)
希望这可以帮助
推荐阅读
- php - Angularjs 组合框值表单提交
- ruby-on-rails - 如何destroy_all 仅依赖于模型而不依赖于模型本身
- java - 使用自定义方法实现 JpaRepository 接口
- python - 为什么 XGBoost 没有显示正确的 best_iteration 和 ntree_limit?
- c++ - 从 C++ 中的头文件调用函数时出现 LNK2019 错误
- python - Python 中的 AWS Lambda:在 Lambda 函数处理程序中导入父包/目录
- php - PHP,使用 Ajax 无法调用其他目录中的 php 文件
- stm32 - stm32H474I 无法调试
- appium - 对于使用 react native 创建的 iOS 应用程序,无法使用 xpath 结尾在 appium 中定位元素
- javascript - 使用从 JavaScript 传递的值数组填充下拉列表