android - TextView 未在自定义 View 中更新

标签 android android-fragments textview

我有一个获取 GPS 信号并将结果发送到自定义 View 的 fragment 。

我可以显示 fragment 中获取的信号的输出,并看到它更新得很好。这是 fragment 1 的代码:

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {

            RelativeLayout view = (RelativeLayout) inflater.inflate(R.layout.gps_stamp_fragment, container,false);
            RelativeLayout rl1 = new RelativeLayout(view.getContext());
            TextView tView1 = new TextView(view.getContext());
            tView1.setText("waiting...");  //this is the only thing custom view gets!
            rl1.addView(tView1);
            rl1.setId(1);
            tView1.setId(2);
            view.addView (rl1);

            lm =(LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 1, this);


            return view;
        }

//And here's where I get the GPS signal from and use setText again to update to the GPS signal.

   @Override
    public void onLocationChanged(Location arg0) {
        String lat = String.valueOf(arg0.getLatitude());

        RelativeLayout rl1 = (RelativeLayout) getView().findViewById(1);
        TextView tView1 = (TextView) rl1.findViewById(2);
        tView1.setText(lat);

    }

然后,在自定义 View 中,我使用以下代码查找相关布局和关联的 TextView 并获取文本。

RelativeLayout rl1 = (RelativeLayout) getRootView().findViewById(1);
TextView tView1 = (TextView) rl1.findViewById(2);  
tView1.getText();
getRootView().invalidate();

问题是这个自定义 View 中出现的唯一文本是“等待...”。 GPS 测量值永远不会出现。

我读过类似的问题,我需要 .invalidate() View ,这就是我添加最后一行的原因,但这似乎对我不起作用。

为什么从 fragment1 调用时 TextView 正确更新,但从自定义 View 调用时却不正确?

谢谢。

最佳答案

invalidate 应该在 onLocationChanged

关于android - TextView 未在自定义 View 中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14927918/

相关文章:

android - 如何在 Android 中将 Fragments 添加到后台堆栈

android - 连接阿拉伯语和英语文本android TextView

Android-平滑地增加 TextView 中的文本大小

android - 在手指触摸上移动 textview 作为拖放 :android

android - 如何使 view.getDrawingCache() 保持透明度

java - 你如何在 Android 中创建一个静态表?

java - 位图空指针异常 bitmap = content.getDrawingCache();

android - Fragment 生命周期中的 onCreateOptionsMenu

java - BottomSheetDialogFragment关闭监听器

android - 禁用应用程序的 Android O 自动填充服务