onSensorChanged中的addContentView会导致错误

时间:2014-04-26 01:11:24

标签: java android surfaceview android-sensors surfaceholder

我有MyCompassView类扩展了视图,它绘制了一个指南针SurfaceHolder活动,可以在表面支架上打开相机,最后,MainActivity应该由上述类重叠。我用SurfaceHolder覆盖MainActivity活动的方式如下

myCameraSurfaceHolder = new SurfaceHolderActivity(this); setContentView(myCameraSurfaceHolder);它可以找到并且相机在表面支架上工作正常。

问题是当我尝试用MainActivity的视图覆盖MyCompassView的表面时。为了达到我的目的:

loiViewInflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); loiViewInflater = LayoutInflater.from(getApplicationContext()); compassOverLayView = loiViewInflater.inflate(R.layout.activity_viewactivity, null); addContentView(compassOverLayView,new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));

addContentView(....)位于传感器监听器的onSensorChanged内,因为每次从传感器读取时我都想根据方位角值绘制不同指针方向的指南针。并且logcat会抱怨并生成以下消息。请帮我纠正错误。

Logcat_OutPut:

04-26 04:07:21.295: E/AndroidRuntime(26921): FATAL EXCEPTION: main
04-26 04:07:21.295: E/AndroidRuntime(26921): java.lang.IllegalStateException: The  
specified child already has a parent. You must call removeView() on the child's parent  
first.
04-26 04:07:21.295: E/AndroidRuntime(26921):    at  
android.view.ViewGroup.addViewInner(ViewGroup.java:3739)
04-26 04:07:21.295: E/AndroidRuntime(26921):    at  
android.view.ViewGroup.addView(ViewGroup.java:3610)
04-26 04:07:21.295: E/AndroidRuntime(26921):    at  
android.view.ViewGroup.addView(ViewGroup.java:3586)
04-26 04:07:21.295: E/AndroidRuntime(26921):    at   
com.android.internal.policy.impl.PhoneWindow.addContentView(PhoneWindow.java:392)
04-26 04:07:21.295: E/AndroidRuntime(26921):    at   
android.app.Activity.addContentView(Activity.java:2004)
04-26 04:07:21.295: E/AndroidRuntime(26921):    at  

android.support.v7.app.ActionBarActivity.superAddContentView(ActionBarActivity.java:228)

1 个答案:

答案 0 :(得分:0)

错误日志显示:“The specified child already has a parent. You must call removeView() on the child's parent first”。

该错误是指已添加到父视图但无法再次添加的compassOverLayView

这不是刷新UI元素的好方法,addContentView并不是要重复调用。

如果您已创建自定义视图以显示指南针,请尝试向其添加刷新方法,然后只需调用它。