【问题标题】:GoogleMap Fragment in ActionBar Tabs (with ActionBarSherlock)ActionBar 选项卡中的 GoogleMap 片段(使用 ActionBarSherlock)
【发布时间】:2023-03-09 05:46:01
【问题描述】:

我遇到了一个(我敢肯定)愚蠢的问题,可以用另一双眼睛。

我有一个应用程序需要在应用程序的多个位置显示 GoogleMaps。我已经在我的主要活动中成功展示了它,所有 Play 库都已就位,V2 密钥已全部设置,等等。

我的(截断的)mapview.xml 看起来像:

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.SupportMapFragment" />

正如我所说,在主Activity上,我可以正确设置contentView并绘制地图,没问题。

但是,在不同的活动中,我正在实现选项卡:

    ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Add tabs
    actionBar.addTab(actionBar.newTab().setText(R.string.map).setTabListener(this));

这就是我遇到麻烦的地方。在选项卡选择的侦听器上,我执行以下操作,我确定这会出错(布局是一个空的线性布局):

    GoogleMapFragment mapFragment = new GoogleMapFragment();
    fragmentTransaction = supportFragmentManager.beginTransaction();
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.replace(layout.getId(), mapFragment);
    fragmentTransaction.commit();

那个地图片段看起来像:

@Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.map_view, null);
  }

当它运行时,我会收到各种错误,具体取决于我如何调整它,例如

android.view.InflateException: Binary XML file line #2: Error inflating class fragment
Caused by: java.lang.IllegalArgumentException: Binary XML file line #2: Duplicate id 0x7f040058, tag null, or parent id 0x0 with another fragment for com.google.android.gms.maps.SupportMapFragment

就像我说的,我确定这是错误的,我似乎在尝试对片段进行两次膨胀,或者在应用程序的两个位置使用相同的片段时可能会遇到问题。

目前我不确定如何解决它。任何建议将不胜感激。

【问题讨论】:

标签: android google-maps android-actionbar actionbarsherlock fragment


【解决方案1】:

您已经在 xml 文件中定义了片段的布局,因此您不必在运行时添加它,只需将片段布局(在您的情况下为 mapview.xml)作为参数传递给您的活动的 setContentView .

【讨论】:

  • 实际上我看不到您在代码中使用 mapFragment 的位置。
  • 抱歉,有错字,已更正。我在 replace() 调用中使用它。
  • GoogleMapFragment 扩展了什么类?
【解决方案2】:

尝试在布局中使用 MapView 而不是 Fragment。

<com.google.android.gms.maps.MapView
    android:id="@+id/map_view"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

【讨论】:

  • MapView 在 v2 中已弃用;它在这里也不起作用。不过谢谢你的建议!