我使用此代码创建地图和标记但是当我运行它时会显示空白地图和错误
我的代码来自 - https://developers.google.com/maps/documentation/android-api/
ContactFragment.java
public class ContactFragment extends Fragment implements OnMapReadyCallback {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.mapView);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap map) {
LatLng sydney = new LatLng(-33.867, 151.206);
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));
map.addMarker(new MarkerOptions()
.title("Sydney")
.snippet("The most populous city in Australia.")
.position(sydney));
}
}
fragment_contact.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="layout.ContactFragment"
android:background="@color/colorWhite"
android:id="@+id/contact_wrapper">
<!-- TODO: Update blank fragment layout -->
<com.google.android.gms.maps.MapView
android:layout_width="match_parent"
android:id="@+id/mapView"
android:layout_height="200dp" />
<TextView
android:text="Address - 1526 Petchaburi Rd. Makkasan Rajdhevee Bangkok 10400 Thailand"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView6"
android:layout_below="@+id/mapView"
android:layout_alignParentStart="true"
android:layout_marginTop="18dp"
android:padding="10dp"
android:textSize="18sp"
android:textStyle="normal|bold" />
<TextView
android:text="Tel - +66-2652-7477-80, Fax +66-2652-7777"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView7"
android:padding="10dp"
android:layout_below="@+id/textView3"
android:layout_alignParentStart="true"
android:textSize="18sp"
android:textStyle="normal|bold"
android:fontFamily="sans-serif" />
<TextView
android:text=" EMail - sdschool@sd.ac.th"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView3"
android:padding="10dp"
android:textSize="18sp"
android:layout_below="@+id/textView6"
android:layout_alignParentStart="true"
android:textStyle="normal|bold" />
</RelativeLayout>
答案 0 :(得分:3)
使用以下代码。
public class ContactFragment extends Fragment implements OnMapReadyCallback {
View rootView
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
rootView =inflater.inflate(R.layout.content_main, container, false);
MapFragment mapFragment = (MapFragment) getFragmentManager()
rootView.findFragmentById(R.id.mapView);
mapFragment.getMapAsync(this);
return rootView;
}
}
答案 1 :(得分:2)
创建Fragment时必须使用onCreateView()回调来定义布局。