问题描述
我有一个名为 SpeedometerFragment
的片段,它具有相应的 XML 布局 fragment_speedometer
然后我创建了一个名为 fragment_distance
的独立布局。没有与此 XML 文件相关联的活动。
我想通过 fragment_distance
中的函数调用更改 SpeedometerFragment
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 文件
我在我的主要活动中创建了一个 public static TextView distance
。
然后在我的片段中,当距离的值发生变化时,我使用 Eye_Tracking_Main.distance.setText(new DecimalFormat("#.#").format(distance) + " Km");
来设置 TextView 的值
在我的主要活动中,我只是使用了 distance=findViewById(R.id.distancemain);