【问题标题】:Delete a view and recreate it删除视图并重新创建它
【发布时间】:2011-03-07 06:15:13
【问题描述】:

有没有办法删除设置的视图

setContentView(R.layout.set_map_center);
mapView = (MapView) findViewById(R.id.mapview);

如果我再次调用此视图,则会收到一条错误消息:

java.lang.IllegalStateException: 你 只允许拥有一个 MapActivity 中的 MapView

【问题讨论】:

  • “如果我再次调用此视图”是什么意思?你的意思是通过 findViewById ?
  • 其实我觉得错误就在:setContentView(R.layout.set_map_center);

标签: android


【解决方案1】:
((ViewGroup)mapView.getParent()).removeView(mapView);

【讨论】:

  • 这个不行,错误还在。我在重新加载设置屏幕时调用它,它仍然有同样的错误。
  • 这只是对您的问题“有没有办法删除视图”的回答;-) 您发布的代码不足以查看错误发生的位置。您应该发布更多代码,实际上是引发异常的部分。
  • 目前还不是很清楚你真正想要达到的目标。如果您实际上不需要它/想要删除它,为什么不首先从您的 xml 布局中删除它?
  • 这里是所有代码(mapView = (MapView) findViewById(R.id.mapview); 创建异常):stackoverflow.com/questions/5216046/…
【解决方案2】:

试试这个.. 首先通过以下代码为您尝试在 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

【讨论】:

  • layout.setVisibility(GONE) 不会删除视图。您需要调用 parentView.removeView(viewToDelete); - 这确实删除了视图,“View.GONE”只是让用户的视图消失,但它没有被删除。
  • 我在 VISIBLE 上遇到错误,我需要导入什么包来支持它?
  • 我仍然收到可见错误,这是 Eclipse 要求我做的:LinearLayout layout = new LinearLayout(getBaseContext());布局.setVisibility(可见); v = View.inflate(getBaseContext(), R.layout.set_map_center, 布局); FrameLayout.LayoutParams 参数 = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); params.gravity = Gravity.NO_GRAVITY; addContentView(布局,参数); v.setVisibility(可见); layout.setVisibility(VISIBLE);
【解决方案3】:

我认为每个人都说得对,对我来说这似乎是 API 中的一个缺陷。我应该能够为视图充气并在其中使用地图,如果我记得该视图然后可以删除它或再次查看它而不会出错。

最简单的解决方法是使用 xml 删除通货膨胀或 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);

这很好用,让我有机会调用地图。感谢大家的回复。

【讨论】:

    猜你喜欢
    • 2018-10-31
    • 2016-01-06
    • 1970-01-01
    • 2015-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-28
    相关资源
    最近更新 更多