我试图在另一个片段中显示谷歌地图片段,但是我无法操纵地图,我已经把我看到的所有步骤都放在了 the documentation,但我不能操纵我的地图。
XML代码:
<FrameLayout 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=".FragmentoPrincipalUsuario">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal|top">
<fragment
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="391dp"
class="com.google.android.gms.maps.MapFragment"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginTop="60dp" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="149dp"
android:layout_gravity="center_horizontal|bottom">
<Button
android:layout_width="117dp"
android:layout_height="wrap_content"
android:text="pedir taxi"
android:id="@+id/pedirTaxi"
android:layout_gravity="center_horizontal" />
</LinearLayout>
类片段代码:
public class FragmentoPrincipalUsuario extends Fragment implements OnMapReadyCallback {
private OnFragmentInteractionListener mListener;
private List<ParseUser> mChoferes;
private ParseUser mUsuarioActual;
private Button mPedido;
private GoogleMap map;
public FragmentoPrincipalUsuario() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//conseguir usuario actual
// mUsuarioActual = ParseUser.getCurrentUser();
View x = inflater.inflate(R.layout.fragmento_principal_usuario, container, false);
//evento boton pedir taxi
mPedido.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("tipoUsuario", "chofer");
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> choferes, com.parse.ParseException e) {
if (e == null) {
mChoferes = choferes;
String nombreChofer;
for (ParseUser chofer : mChoferes) {
nombreChofer = chofer.getUsername();
ParseObject gameScore = new ParseObject("Viaje");
gameScore.put("cliente", "hola");
gameScore.put("chofer", nombreChofer);
gameScore.put("tomado", false);
gameScore.saveInBackground();
}
} else {
// Something went wrong.
}
}
});
}
});
// Inflate the layout for this fragment
return x;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onMapReady(GoogleMap map) {
LatLng sydney = new LatLng(-27.7933121, -64.2574857);
map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
主要活动类代码:
public class DrawerPrincipal extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,FragmentoPrincipalUsuario.OnFragmentInteractionListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer_principal);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//cargar fragment principal usuario
Fragment fragmento= null;
fragmento = new FragmentoPrincipalUsuario();
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_main, fragmento)
.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.pantalla_principal_usuario, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.cuenta) {
// Handle the camera action
} else if (id == R.id.historial_viajes) {
} else if (id == R.id.contacto) {
} else if (id == R.id.compartir) {
} else if (id == R.id.version) {
} else if (id == R.id.salir) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void onFragmentInteraction(Uri uri) {
}
}
编辑,在调用getMapAsync()之后,这里是堆栈跟踪:
nullpointer错误:
12-18 19:51:50.056 11265-11265 / ar.com.taxiexpress.taxiexpress E / AndroidRuntime:FATAL EXCEPTION:main java.lang.RuntimeException: 无法开始活动 ComponentInfo {ar.com.taxiexpress.taxiexpress / ar.com.taxiexpress.taxiexpress.DrawerPrincipal}: java.lang.NullPointerException at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 在android.app.ActivityThread.access $ 600(ActivityThread.java:141)at android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1234) 在android.os.Handler.dispatchMessage(Handler.java:99)at android.os.Looper.loop(Looper.java:137)at android.app.ActivityThread.main(ActivityThread.java:5041)at java.lang.reflect.Method.invokeNative(Native Method)at java.lang.reflect.Method.invoke(Method.java:511)at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:793) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)at dalvik.system.NativeStart.main(Native方法)引起: java.lang.NullPointerException at ar.com.taxiexpress.taxiexpress.FragmentoPrincipalUsuario.onCreateView(FragmentoPrincipalUsuario.java:61) 在 android.support.v4.app.Fragment.performCreateView(Fragment.java:1962) 在 android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067) 在 android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248) 在 android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738) 在 android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613) 在 android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:330) 在 android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:547) 在 android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1164) 在android.app.Activity.performStart(Activity.java:5114)处 android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2153) 在 android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230) 在android.app.ActivityThread.access $ 600(ActivityThread.java:141)at android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1234) 在android.os.Handler.dispatchMessage(Handler.java:99)at android.os.Looper.loop(Looper.java:137)at android.app.ActivityThread.main(ActivityThread.java:5041)at java.lang.reflect.Method.invokeNative(Native Method)at java.lang.reflect.Method.invoke(Method.java:511)at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:793) 在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)at dalvik.system.NativeStart.main(原生方法)
答案 0 :(得分:0)
看起来主要的问题是你没有调用getMapAsync()。
由于您在Fragment中使用嵌套的SupportMapFragment,因此您需要使用getChildFragmentManager()
来获取Map Fragment,然后调用getMapAsync()
。
SupportMapFragment mapFragment = ((SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map));
mapFragment.getMapAsync(this);
然而,虽然这样可行,但最好让Fragment扩展SupportMapFragment,这样你就不需要嵌套片段了:
public class MyMapFragment extends SupportMapFragment
implements OnMapReadyCallback {
private GoogleMap mMap;
private Marker marker;
public MyMapFragment () {
}
@Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
getMapAsync(this);
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
setUpMap();
}
private void setUpMap() {
mMap.setMyLocationEnabled(true);
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mMap.getUiSettings().setMapToolbarEnabled(false);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
//remove previously placed Marker
if (marker != null) {
marker.remove();
}
//place marker where user just clicked
marker = mMap.addMarker(new MarkerOptions().position(point).title("Marker")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA)));
}
});
}
}