android - 如何从在 XML 中创建的 SupportMapFragment 获取 GoogleMap 对象? API 级别 8

标签 android android-layout fragment

我正在尝试从 SupportMapFragment 对象获取 GoogleMap 对象。因为我也想在 API 级别 8 上工作,所以像 findFragmentById 这样的解决方案对我不起作用..

我有这个 XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:background="#fff"
   android:id="@+id/map_view"
   android:layout_height="match_parent" >
<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"
      android:name="com.google.android.gms.maps.SupportMapFragment"
      map:cameraZoom="11"
      map:cameraTargetLat="32.1275701"
      map:cameraTargetLng="34.7983432"
      map:uiZoomControls="false"/>

   <ImageView
        android:id="@+id/button_image"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:gravity="bottom"    
        android:contentDescription="@string/back"    
        android:layout_alignParentBottom="true"
        android:clickable="true"
        android:onClick="returnToMain"
        android:background="@drawable/return_button" />
    </RelativeLayout>

更新:

Java代码:

public void category(View v){
    if(isNetworkAvailable()){
        if(viewMap==null){
            setContentView(R.layout.map_view);
            viewMap=(RelativeLayout)findViewById(R.id.map_view);
            Fragment ssmf=getFragmentManager().findFragmentById(R.id.map);
            mapObject=((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
            mapObject.addMarker(new MarkerOptions()
            .position(new LatLng(32.1275701, 34.7983432))
            .title("Hello world"));
        }
        else{
            setContentView(viewMap);
        }
    }
}

我遇到了这个错误:

无法将 Fragment 形式转换为 SupportMapFragment

最佳答案

在使用 SupportFragments 时使用 getSupportFragmentManager()。

关于android - 如何从在 XML 中创建的 SupportMapFragment 获取 GoogleMap 对象? API 级别 8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14128099/

相关文章:

android - 状态更改后未调用 Flutter Bloc Builder 且未更新 UI

android - picasso 无法加载专辑封面

java - XML 资源中的变量 - 将值从父级传递给子级

java - 如何以编程方式更改 RecyclerView 项目属性,特别是 recyclerview 项目内的自定义 View

android - 多个屏幕尺寸的 TableLayout?

android - 迁移 android X androidx.appcompat.widget.SearchView 后获取 null

android - TableLayout 为每一行设置样式

android - 如何实现Android Fragment Transaction .add语法错误

c# - Xamarin Android - OutOfMemoryError 异常 - 大图

交易后 Android Fragment 不膨胀