从片段函数更改 TextView 的值

Change value of TextView from fragment function

我有一个名为 SpeedometerFragment 的片段,它有各自的 XML 布局 fragment_speedometer

然后我创建了一个名为 fragment_distance 的独立布局。没有与此 XML 文件关联的 activity。

我想通过 SpeedometerFragment.

中的函数调用更改 fragment_distance XML 文件中文本视图“distanceText”的值

fragment_distance 被传递到我的主 activity 中的 frameLayout。

我在 SpeedometerFragment 的 onCreateView 中尝试了以下操作,但文本视图没有变化:

速度计片段


       LayoutInflater inflater1 = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater1.inflate(R.layout.fragment_distance, container, false);
        TextView dis = (TextView) v.findViewById(R.id.distanceText);
        dis.setText("Test");

我想出了一个解决办法。我在原来的问题中把它复杂化了,所以不需要膨胀任何东西,也不需要单独的 fragment_distance XML 文件

我在主 activity 中创建了一个 public static TextView distance

然后在我的片段中,当 distance 的值发生变化时,我使用 Eye_Tracking_Main.distance.setText(new DecimalFormat("#.#").format(distance) + " Km"); 来设置 TextView

的值

在我的主要 activity 中,我只是使用了 distance=findViewById(R.id.distancemain);