1
我在這裏寫了一個Android碎片下面的代碼:我該如何去做map!= null?
的Java文件:
package com.WolfDev.ExercisePlanner;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.app.Fragment;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
/**
* Created by WolfDev on 4/14/2014.
*/
public class TrackerFragment extends Fragment {
private GoogleMap googleMap;
//private boolean chronoRunning = false;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag3_action, container, false);
SupportMapFragment supportMapFragment = SupportMapFragment.newInstance();
googleMap = supportMapFragment.getMap();
//googleMap.setMyLocationEnabled(true);
android.support.v4.app.FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.map, supportMapFragment).commit();
activityBody();
return rootView;
}
版式文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="6"
android:id="@+id/map"
class="com.google.android.gms.maps.MapFragment" >
</fragment>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1">
<Chronometer
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/chronometer"
android:text="@+id/chronometerDisplay"
android:gravity="center" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1">
<Button
android:layout_width="0px"
android:layout_height="match_parent"
android:text="START/STOP"
android:id="@+id/btnStartStop"
android:layout_weight="1"/>
<Button
android:layout_width="0px"
android:layout_height="match_parent"
android:text="LAP/RESET"
android:id="@+id/btnLapReset"
android:layout_weight="1"/>
</LinearLayout>
</LinearLayout>
正如你可以在代碼中看到的,我有這樣的行已註釋掉:
//googleMap.setMyLocationEnabled(true);
當它未被註釋掉時,我得到一個NullPointerException錯誤。我的研究表明,它正在發生,因爲變量googleMap爲空。我該如何糾正這一點,使其不再爲空?
你在哪裏得到來自mapFragment?我沒有這個名字的變量。 – Patr3xion
@ Patr3xion我想你會想將'SupportMapFragment.newInstance()'分配給一個字段而不是局部變量。 –