gpt4 book ai didi

android - 当我尝试设置MapType 时,MapFragment 使应用程序在运行时崩溃

转载 作者:行者123 更新时间:2023-12-02 11:39:20 25 4
gpt4 key购买 nike

我在尝试更改 Android 应用程序中的 GoogleMap 类型时遇到问题。我有一个基本的操作栏菜单,当我在操作栏中选择正确的选项时,我希望将 map 作为 fragment 放置在我的 Activity 中。这是我的代码:

package com.example.where2go;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MainActivity extends FragmentActivity {

private MahMapFrag mapFragment;

@Override
public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

try {

initializeMap();

} catch (Exception e) {e.printStackTrace();}

}

private boolean initializeMap() {
if (mapFragment == null) {

mapFragment = new MahMapFrag();
// check if map is created successfully or not
try{
if (mapFragment == null) {
Toast.makeText(getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
return false;
}
else {
Log.d("MLOGS", "Map Intitialized");
return true;
}
} catch(Exception e) {
e.printStackTrace();
}
}
return false;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_map:
getFragmentManager().beginTransaction().replace(android.R.id.content,mapFragment).commit();
break;
default:
return false;
}
return true;
}

}

这是我扩展 MapFragment 的类:

package com.example.where2go;

import android.util.Log;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;

public class MahMapFrag extends MapFragment {

public MahMapFrag() {
Log.d("MLOGS", "CONSTRUCT");
//this.getMap().setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}

}

当行

this.getMap().setMapType(GoogleMap.MAP_TYPE_SATELLITE);

被评论,应用程序(似乎)运行顺利。但是,当该行取消注释时,如果我尝试在构造函数中更改 map 的类型,则当我单击操作栏时,应用程序会崩溃,这会调用

getFragmentManager().beginTransaction().replace(android.R.id.content,mapFragment).commit();

我在 com.where2go.MainActivity.onOptionItemSelected 处出现空指针异常。当我设置 map 类型时,它已经尝试了几个小时来找出为什么我的mapFragment为空。

有人可以给我关于这个问题的线索和/或解释吗?我真的很想了解,因为我感觉我错过了一些对于进一步的 android 开发至关重要的东西......

我使用安装了 Google Play 服务的 eclipse Juno 和 Genymotion,并使用 API 19 进行编译。

谢谢

科亚

最佳答案

确保您正在使用“我发现这对我的案例有帮助”。 (引用你的 MahMapFrag 哈哈)

fragmentManager = getSupportFragmentManager();

将其添加到您的 xml

   <fragment
android:id="@+id/location_map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.SupportMapFragment" />

关于android - 当我尝试设置MapType 时,MapFragment 使应用程序在运行时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26552811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com