Android 删除视图并重新创建它

Android 删除视图并重新创建它,android,Android,是否有方法删除设置为的视图 setContentView(R.layout.set_map_center); mapView = (MapView) findViewById(R.id.mapview); 如果我再次调用此视图,则会出现一个错误,提示: java.lang.IllegalStateException:您 只允许有一间单人房 MapActivity中的MapView 试试这个。。 首先,通过以下代码在setContentView()中对您试图设置的视图进行充气 layout =

是否有方法删除设置为的视图

setContentView(R.layout.set_map_center);
mapView = (MapView) findViewById(R.id.mapview);
如果我再次调用此视图,则会出现一个错误,提示:

java.lang.IllegalStateException:您 只允许有一间单人房 MapActivity中的MapView

试试这个。。 首先,通过以下代码在setContentView()中对您试图设置的视图进行充气

layout = new LinearLayout(context);
    layout.setVisibility(VISIBLE);
    v = View.inflate(getContext(), R.layout.set_map_center, layout);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.NO_GRAVITY;
    addView(layout, params);
    v.setVisibility(VISIBLE);
layout.setVisibility(VISIBLE);
无论何时,只要想删除视图,就可以简单地说layout.setVisibility(GONE)
如果您无法访问GONE,请说View.GONE

我认为每个人都有点正确,这对我来说就像API中的一个缺陷。我应该能够膨胀一个视图并在其中使用地图,如果我调用该视图,则能够删除它或再次查看它,而不会出错

((ViewGroup)mapView.getParent()).removeView(mapView);
最简单的解决方法是使用xml删除inflation或setContentView,然后动态构建地图,然后将其存储在内存中

我已删除:

// Show Map Settings Screen
setContentView(R.layout.set_map_center);

// Initiate the center point map
if (mapView == null) {
    mapView = (MapView) findViewById(R.id.mapview);
}
if (mapView == null) {
   // public MapView mapView = null; // Public defined Variable
   mapView = new MapView(this, this.getString(R.string.APIMapKey));
}

setContentView(mapView);
并将其替换为:

// Show Map Settings Screen
setContentView(R.layout.set_map_center);

// Initiate the center point map
if (mapView == null) {
    mapView = (MapView) findViewById(R.id.mapview);
}
if (mapView == null) {
   // public MapView mapView = null; // Public defined Variable
   mapView = new MapView(this, this.getString(R.string.APIMapKey));
}

setContentView(mapView);

这很有效,让我有机会打电话给地图。谢谢大家的回复。

如果我再次调用此视图,您是什么意思?你是说通过findViewById?事实上,我认为错误在:setContentView(R.layout.set\u map\u center);layout.setVisibility(GONE)不会删除视图。您需要调用parentView.removeView(viewToDelete);-这确实删除了视图,“view.GONE”只会让用户的视图消失,但不会被删除。我在VISIBLE上遇到错误,我需要导入什么包来支持它?我在VISIBLE上仍然遇到错误,Eclipse要求我做的是:LinearLayout=new LinearLayout(getBaseContext());布局。设置可见性(可见);v=视图。充气(getBaseContext(),R.layout.set\u map\u center,layout);FrameLayout.LayoutParams params=新的FrameLayout.LayoutParams(LayoutParams.WRAP_内容,LayoutParams.WRAP_内容);参数重力=重力。无重力;addContentView(布局、参数);v.可视性(可见);布局。设置可见性(可见);这不起作用,错误仍然存在。当设置屏幕重新加载时,我会调用它,但它仍然有相同的错误。这只是对您的问题“有办法删除视图吗”;-)您发布的代码不足以查看错误发生的位置。您应该发布更多的代码,实际上是引发异常的部分。您实际上想要实现什么还不是很清楚。如果实际上不需要mapview/无论如何都想删除它,为什么不首先从xml布局中删除它?以下是所有代码(mapview=(mapview)findViewById(R.id.mapview);创建异常):