草庐IT

java - Google Maps Fragment 无法加载

coder 2023-11-29 原文

我想加载 Google Maps对象并创建一些监听器:

我创建了这个类:

import java.lang.ref.WeakReference;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewParent;
import android.widget.ImageView;
import android.widget.Toast;

public class itemSaleActivity extends FragmentActivity  {
    private static Context app;
    private static GoogleMap map;
    static final LatLng HAMBURG = new LatLng(53.558, 9.927);
    private static final int LOAD_COORD = 0;
    private ImageView pic;
    private LocationHandler mHandler;

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        // Set View to register.xml
        setContentView(R.layout.itemsale);

        app = getApplicationContext();
        Bundle extras = getIntent().getExtras();
        byte[] byteArray = extras.getByteArray("picture");
        Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);

        pic = (ImageView) findViewById(R.id.itemImage);
        pic.setImageBitmap(bmp);

        map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
        //Marker hamburg = map.addMarker(new MarkerOptions().position(HAMBURG).title("Hamburg"));
        mHandler = new LocationHandler(this);

        OnMarkerDragListener markerDragListener = new OnMarkerDragListener() {

            @Override
            public void onMarkerDragStart(Marker marker) {
                // Called when the marker drag is started
            }

            @Override
            public void onMarkerDragEnd(Marker marker) {
                // Called when the marker is dropped down.
                double[] coords = null;
                coords[0] = marker.getPosition().latitude;
                coords[1] = marker.getPosition().longitude;
                RestoreUIwithSavedLocation(coords);
                Toast.makeText(getApplicationContext(),"Pin Dropped at: " + coords[0] + ", " + coords[1]+marker.getTitle() , Toast.LENGTH_LONG).show();
            }

            @Override
            public void onMarkerDrag(Marker marker) {

            }
        };

        map.setOnMarkerDragListener(markerDragListener);

        View titleView = getWindow().findViewById(android.R.id.title);
        if (titleView != null) {
            ViewParent parent = titleView.getParent();
            if (parent != null && (parent instanceof View)) {
             View parentView = (View)parent;
             parentView.setVisibility(View.GONE);
            }
        }

        // You can also assign the title programmatically by passing a
        // CharSequence or resource id.
    }

    private void RestoreUIwithSavedLocation(double[] coordsArray) {
        Message.obtain(mHandler, LOAD_COORD, coordsArray).sendToTarget();
    }

    static class LocationHandler extends Handler {
        WeakReference<Activity> mActivity;

        public LocationHandler(Activity activity) {
            mActivity = new WeakReference<Activity>(activity);
        }

        public void handleMessage(Message msg) {
            Activity contextActivity = mActivity.get();
            switch ((int)msg.what) {

            case LOAD_COORD:
                map.clear();
                double[] coordArray = (double[])msg.obj;
                Marker marker = map.addMarker(new MarkerOptions().position(new LatLng(coordArray[0], coordArray[1])));
                map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(coordArray[0], coordArray[1]), 18));
                map.animateCamera(CameraUpdateFactory.zoomTo(18), 2000, null);
                marker.setDraggable(true);
                String s = Double.toString(coordArray[0]) + ", " + Double.toString(coordArray[1]);
                Toast.makeText(app,"in the case"+s , Toast.LENGTH_LONG).show();
                break;
            }
        }
    }
}

这是 XML:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/itemImage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:src="@drawable/logo" />

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="400dp"
        android:layout_marginTop="10dp"
        android:layout_weight="66496.79"
        android:orientation="horizontal" >

        <fragment
            android:id="@+id/map"
            class="com.google.android.gms.maps.MapFragment"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginRight="150dp" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="170dp"
            android:orientation="vertical" >

            <Button
            android:id="@+id/messageBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:text="fffff" />

            <Button
                android:id="@+id/call"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentRight="true"
                android:text="ffff" />

        <Button
            android:id="@+id/sms"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignRight="@+id/button1"
            android:layout_centerVertical="true"
            android:text="ffff" />
        <Button
            android:id="@+id/email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignRight="@+id/button1"
            android:layout_centerVertical="true"
            android:text="fffff" />

        <Button
            android:id="@+id/navigate"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/button1"
            android:layout_alignParentEnd="false"
            android:layout_alignParentStart="false"
            android:layout_below="@+id/button1"
            android:layout_marginTop="14dp"
            android:text="ffffffffff" />
        </LinearLayout>
    </RelativeLayout>
</LinearLayout>

当我在手机 (galaxy s2) 上调试它时,它显示异常:

03-29 15:24:29.750: E/AndroidRuntime(2579): FATAL EXCEPTION: main
03-29 15:24:29.750: E/AndroidRuntime(2579): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sal/com.example.sal.itemSaleActivity}: android.view.InflateException: Binary XML file line #26: Error inflating class fragment
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2079)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.app.ActivityThread.access$600(ActivityThread.java:132)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1157)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.os.Looper.loop(Looper.java:137)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.app.ActivityThread.main(ActivityThread.java:4575)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at java.lang.reflect.Method.invokeNative(Native Method)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at java.lang.reflect.Method.invoke(Method.java:511)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at dalvik.system.NativeStart.main(Native Method)
03-29 15:24:29.750: E/AndroidRuntime(2579): Caused by: android.view.InflateException: Binary XML file line #26: Error inflating class fragment
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:697)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:739)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:742)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:251)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.app.Activity.setContentView(Activity.java:1835)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at com.example.sal.itemSaleActivity.onCreate(itemSaleActivity.java:45)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.app.Activity.performCreate(Activity.java:4465)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2033)
03-29 15:24:29.750: E/AndroidRuntime(2579):     ... 11 more
03-29 15:24:29.750: E/AndroidRuntime(2579): Caused by: java.lang.ClassCastException: com.google.android.gms.maps.MapFragment cannot be cast to android.support.v4.app.Fragment
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.support.v4.app.Fragment.instantiate(Fragment.java:388)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.support.v4.app.Fragment.instantiate(Fragment.java:363)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:264)
03-29 15:24:29.750: E/AndroidRuntime(2579):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:669)
03-29 15:24:29.750: E/AndroidRuntime(2579):     ... 22 more

xml 文件中的第 26 行是:

  <fragment
                android:id="@+id/map"
                class="com.google.android.gms.maps.MapFragment"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_marginRight="150dp" />

最佳答案

在 XML 文件中,使用 class="com.google.android.gms.maps.SupportMapFragment"

在你的主类中,使用:

map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

代替:

map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

关于java - Google Maps Fragment 无法加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15703245/

有关java - Google Maps Fragment 无法加载的更多相关文章

  1. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  2. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  3. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  4. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  5. ruby-on-rails - 无法在centos上安装therubyracer(V8和GCC出错) - 2

    我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e

  6. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  7. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  8. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  9. ruby - 无法覆盖 irb 中的 to_s - 2

    我在pry中定义了一个函数:to_s,但我无法调用它。这个方法去哪里了,怎么调用?pry(main)>defto_spry(main)*'hello'pry(main)*endpry(main)>to_s=>"main"我的ruby版本是2.1.2看了一些答案和搜索后,我认为我得到了正确的答案:这个方法用在什么地方?在irb或pry中定义方法时,会转到Object.instance_methods[1]pry(main)>defto_s[1]pry(main)*'hello'[1]pry(main)*end=>:to_s[2]pry(main)>defhello[2]pry(main)

  10. ruby - 无法在 60 秒内获得稳定的 Firefox 连接 (127.0.0.1 :7055) - 2

    我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类

随机推荐