【问题标题】:Navigation Drawer unable to take to specific location in maps fragment in androidNavigation Drawer 无法到达 android 地图片段中的特定位置
【发布时间】:2014-09-08 20:32:40
【问题描述】:

好的,所以我的应用中有一个片段中的地图和一个导航抽屉。地图在应用程序运行时加载并指向当前位置。现在,我在导航列表中添加了几个地方及其经纬度。现在我要做的就是每当我在导航抽屉中单击其中一个这样的地方时,它就会将我带到那个地方,而无需再次加载地图片段,也无需更改地图上的当前设置标记。

这是在导航抽屉中的每个项目单击时调用的 SelectItem 方法。这个方法存在于我应用的MainActivity中

   public void SelectItem(int possition) {

Fragment fragment = null;
Bundle args = new Bundle();

fragment = new MAPFragment();


Log.e("In main activity","Lets see what happens");



String[] coords = dataList.get(possition).getGeo().split(",");
Double c1 = new Double(Double.valueOf(coords[0])); 
Double c2 = new Double(Double.valueOf(coords[1]));



fragment.setArguments(args);



FragmentManager frgManager = getFragmentManager();
final Fragment existingFragment = frgManager.findFragmentById(R.id.map);


if(existingFragment !=null){

    ((receiveData)existingFragment).navigateToNewLocation(c1,c2);
}
else
 frgManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

mDrawerList.setItemChecked(possition, true);
setTitle(dataList.get(possition).getItemName());
mDrawerLayout.closeDrawer(mDrawerList);

}

这是我的地图片段...

 interface receiveData{
public void navigateToNewLocation(double lat, double lon);}
public class MAPFragment extends Fragment implements receiveData {
public  String IMAGE_RESOURCE_ID = "iconResourceID";
public  String ITEM_NAME = "itemName";
public  String GEO = "39.933333,32.866667";

public void setParameters(double lat, double lon){
  navigateToNewLocation(lat, lon);
}
// Google Map
 private GoogleMap googleMap;
 ImageView ivIcon;
 TextView tvItemName;
 MapView mapView;


String[] coords = GEO.split(",");
Double c1 = new Double(Double.valueOf(coords[0]));
Double c2 = new Double(Double.valueOf(coords[1]));

public MAPFragment() {

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
          Bundle savedInstanceState) {

    View view = inflater.inflate(R.layout.fragment_layout_one, container,
                false);
    Log.e("coords[0]",coords[0]);

    try {
        // Loading map
        initilizeMap();

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

    return view;
 }


 /**
   * function to load map. If map is not created it will create it for you
  * */
 public void initilizeMap() {
  if (googleMap==null){
    googleMap=((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
    googleMap.getUiSettings().setMyLocationButtonEnabled(true);
    googleMap.getUiSettings().setRotateGesturesEnabled(true);
    googleMap.setMyLocationEnabled(true);

    Log.e("In MAPFragment","Before coords!=null");


    googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(c1,c2)));


      LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
      Criteria criteria = new Criteria();
      String provider = locationManager.getBestProvider(criteria, true);
      Location location = locationManager.getLastKnownLocation(provider);

      if(location!=null){
          onLocationChanged(location);
      }

      googleMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {

          @Override
          public void onMyLocationChange(Location arg0) {
              // TODO Auto-generated method stub             
          }
      });

    //checking
    if(googleMap==null){
        Toast.makeText(getActivity().getApplicationContext(), "Unable to create", Toast.LENGTH_SHORT).show();
    }
   }
 }

@Override
public void onResume() {
    super.onResume();
    initilizeMap();
}

 public void onLocationChanged(Location location) {
   // TODO Auto-generated method stub
    // Getting latitude of the current location
   double latitude = location.getLatitude();

  // Getting longitude of the current location
  double longitude = location.getLongitude();

  // Creating a LatLng object for the current location
  LatLng latLng = new LatLng(latitude, longitude);

  // Showing the current location in Google Map
  googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

  // Zoom in the Google Map
  googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));

 }

@Override
public void onDestroyView()
{
    super.onDestroy();
    mapView.onDestroy();
   }

 public void navigateToNewLocation(double lat, double lon){

  Log.e("INSIDE navigateToNewLoc","next is cam pos");
    // On clicking a user       
    CameraPosition cameraPosition = new CameraPosition.Builder().target(
            new LatLng(lat,lon)).zoom(12).build();
     Log.e("INSIDE navigateToNewLoc","next is animateCam");
    googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

 }
  }

现在使用这些代码,每次我点击导航抽屉中的项目时,应用程序都会失败......我猜这是因为 SelectItem 方法中这一行中的 Class Cast Exception 造成的

  ((receiveData)existingFragment).navigateToNewLocation(c1,c2);

这是我的日志猫

    09-10 03:00:00.784: E/AndroidRuntime(31030): FATAL EXCEPTION: main
    09-10 03:00:00.784: E/AndroidRuntime(31030): Process: com.findmeWithdrawer, PID: 31030
    09-10 03:00:00.784: E/AndroidRuntime(31030): java.lang.ClassCastException:         com.google.android.gms.maps.MapFragment cannot be cast to com.findmeWithdrawer.receiveData
    09-10 03:00:00.784: E/AndroidRuntime(31030):  at       com.findmeWithdrawer.MainActivity.SelectItem(MainActivity.java:205)

【问题讨论】:

    标签: android google-maps android-fragments navigation-drawer


    【解决方案1】:

    在创建片段之前,请先尝试查询它是否已存在。例如:

    final Fragment existingFragment = fragmentManager.findFragmentByTag("myfragmentname");
    

    如果不存在则:

     fragmentManager.beginTransaction()
             .replace(R.id.content_frame, fragment,"myfragmentname")
             .commit();
    

    然后,通过实现接收参数的方法(实现接口)将参数传递给片段(无论是否新实例化):

     ((SomeInterface)existingFragment).SetParameters(blah1, blah2, blah3);
    

    你的片段定义实现了这个接口

      public class MAPFragment extends Fragment implements SomeInterface {
        public SetParameters(int blah1, int blah2, int blah3) {
           // do your stuff here...
    

    【讨论】:

    • 嘿,我已经编辑了我上面的代码......你的方法部分工作......但仍然存在 Class Cast Exception......我不知道如何修复它------- java.lang.ClassCastException:com.google.android.gms.maps.MapFragment 无法转换为 com.findmeWithdrawer.receiveData
    • existingFragment 变量的数据类型是什么?是您的 MAPFragment 类(您编写的)还是 Google 的 MapFragment(com.google.android.gms.maps.MapFragment)?尝试在崩溃的行之前添加 LogCat tostring(例如 Log.i("yourtag", existingFragment.getClass().getSimpleName())
    • 嘿,我刚刚添加了 LOG CAT 数据
    猜你喜欢
    • 2014-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多