首页 > 解决方案 > 使用视图模型将数据从活动发送到片段

问题描述

我正在尝试使用片段而不是启动活动在我的主要活动中显示我的数据。这是我的主要活动屏幕

<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);
    }
}

标签: javaandroidandroid-fragments

解决方案


您可以使用 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)

希望这可以帮助


推荐阅读