2017-02-20 7 views
0

Я несколько дней работал над проблемой, но я не могу ее решить. Мне нужна помощь. Я хочу активировать фрагмент карты google из активности, когда на нее нажимается кнопка.Xamarin Android, я хочу активировать фрагмент карты google из активности при нажатии на кнопку

MainActivity Screenshot

MainActivity.cs коды ниже

using Android.App; 
using Android.Content; 
using Android.Widget; 
using Android.OS; 
using Android.Views; 
using System; 
using Android.Media; 
using System.Json; 
using System.Threading.Tasks; 
using System.Net; 
using Android.Locations; 
using System.Collections.Generic; 
using System.Linq; 
using Java.Lang; 
using Newtonsoft.Json; 

namespace gpsCaution 
{ 
    [Activity(Label = "gpsCaution", MainLauncher = true, Icon = "@drawable/gpsCaution")] 
    public class MainActivity : Activity 
    { 
     ...... 
     some codes 
     ...... 

     public static MainActivity Instance; 
     protected override async void OnCreate(Bundle bundle) 
     {   
      base.OnCreate(bundle); 
      Instance = this; 
      SetContentView(Resource.Layout.Main); 

      Button mbuttonShowMap = FindViewById<Button>(Resource.Id.buttonShowMap); 

      mbuttonShowMap.Click += delegate 
      {    
       StartActivity(typeof(Harita)); //** **It crashes here** **// 
      }; 

     ...... 
     some codes 
     ...... 
} 

кодов Main.axml ниже

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:minHeight="25px" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:paddingLeft="10dp" 
    android:paddingTop="10dp" 
    android:id="@+id/duzen"> 
    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/txtLocation" 
     android:width="200dp" 
     android:layout_alignParentRight="true" /> 
    <TextView 
     android:text="Konumunuz:" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/textView1" 
     android:layout_toLeftOf="@id/txtLocation" 
     android:layout_alignTop="@id/txtLocation" 
     android:width="100dp" 
     android:layout_alignParentLeft="true" /> 
    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@id/txtLocation" 
     android:id="@+id/txtAddress" 
     android:width="200dp" 
     android:layout_alignParentRight="true" /> 
    <TextView 
     android:text="Adresiniz:" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:id="@+id/textView2" 
     android:layout_toLeftOf="@id/txtAddress" 
     android:layout_alignTop="@id/txtAddress" 
     android:layout_below="@id/txtLocation" 
     android:width="100dp" 
     android:layout_alignParentLeft="true" /> 
    <TextView 
     android:text="" 
     android:layout_width="wrap_content" 
     android:layout_height="85dp" 
     android:id="@+id/textEmpty" /> 
    <ProgressBar 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_centerInParent="true" 
     android:layout_gravity="bottom" 
     android:id="@+id/progressBar" 
     android:visibility="invisible" /> 
    <Button 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="Harita Görünümü" 
     android:id="@+id/buttonShowMap" 
     android:visibility="visible" 
     android:layout_alignBottom="@id/progressBar" 
     android:layout_alignParentBottom="true" 
     android:layout_marginBottom="10px" 
     android:layout_marginRight="20px" /> 
</RelativeLayout> 

Harita.axml кодов ниже

<?xml version="1.0" encoding="utf-8"?> 
    <fragment xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/googlemap" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    class="com.google.android.gms.maps.MapFragment"/> 

Harita.cs коды ниже

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using Android.App; 
using Android.Content; 
using Android.OS; 
using Android.Runtime; 
using Android.Views; 
using Android.Widget; 
using Android.Gms.Maps; 
using Android.Gms.Maps.Model; 

namespace gpsCaution 
{ 
    [Activity(Label = "Harita")] 
    public class Harita : Activity,IOnMapReadyCallback 
    { 
     public void OnMapReady(GoogleMap googleMap) 
     { 
      MarkerOptions markerOptions = new MarkerOptions(); 
      markerOptions.SetPosition(new LatLng(16.03, 108)); 
      markerOptions.SetTitle("BABALAR"); 
      googleMap.AddMarker(markerOptions); 

      //optional 
      googleMap.UiSettings.ZoomControlsEnabled = true; 
      googleMap.UiSettings.CompassEnabled = true; 
      googleMap.MoveCamera(CameraUpdateFactory.ZoomIn()); 
     }  

     protected override void OnCreate(Bundle bundle) 
     { 
      base.OnCreate(bundle); 
      SetContentView(Resource.Layout.Harita); 

      MapFragment mapFragment = (MapFragment)FragmentManager.FindFragmentById(Resource.Id.googlemap); 
      mapFragment.GetMapAsync(this); 
     }  

    } 
} 

Наконец AndroidManifest.xml коды ниже

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="gpsCaution.gpsCaution" android:versionCode="1" android:versionName="1.0" android:installLocation="preferExternal"> 
    <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="23" /> 
    <application android:label="gpsCaution" android:icon="@drawable/gpsCaution"></application> 
    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
    <uses-permission android:name="android.permission.INTERNET" /> 
    <uses-permission android:name="android.permission.VIBRATE" /> 
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
    <uses-permission android:name="android.permission.WRITE_GSERVICES" /> 
    <uses-permission android:name="com.google.providers.gsf.permission.READ_GSERVICES" /> 
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" /> 
    <uses-permission android:name="gpsCaution.gpsCaution.MAPS_RECEIVE" android:protectionLevel="signature"/> 
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 
    <uses-features android:glEsVersion="0x00020000" android:required="true" /> 

    <application android:label="gpsCaution"> 
    <meta-data android:name="com.google.android.geo.API_KEY" android:value="REMOVED" /> 
    <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> 
    </application>  
</manifest> 

Мой ключ Google API правильно, я уверен, потому что это работает, когда я пишу эти коды в mainactivity без второй активности. Но когда я хочу вызвать фрагмент карты google из основного действия, когда на него нажимается кнопка, у меня случился сбой ошибки «Unhandled Exception: Android.Views.InflateException: двоичная строка XML-файла №1: ошибка раздувания класс фрагмент»

Пожалуйста, помогите, спасибо заранее

ответ

0

Вы использовали неправильную функцию для запуска фрагмента карты. Сначала создайте контейнер фрагмента карты в своем MyMapActivity и используйте FragmentTransaction, чтобы зафиксировать фрагмент карты в контейнере.

Попробуйте следующий код:

создать карту containner в вашем MyMapActivity:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 
    <FrameLayout 
     android:id="@+id/map" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" /> 
</LinearLayout> 

При запуске MyMapActivity, фиксирование фрагмента карты в framelayout:

public class MyMapActivity : Activity,IOnMapReadyCallback 
{ 
    MapFragment _mapFragment; 
    private GoogleMap _map; 
    protected override void OnCreate(Bundle savedInstanceState) 
    { 
     base.OnCreate(savedInstanceState); 
     SetContentView(Resource.Layout.SecondActivity); 
     InitMapFragment(); 
    }  
    private void InitMapFragment() 
    { 
     _mapFragment = FragmentManager.FindFragmentByTag("map") as MapFragment; 
     if (_mapFragment == null) 
     { 
      GoogleMapOptions mapOptions = new GoogleMapOptions() 
       .InvokeMapType(GoogleMap.MapTypeSatellite) 
       .InvokeZoomControlsEnabled(false) 
       .InvokeCompassEnabled(true); 

      FragmentTransaction fragTx = FragmentManager.BeginTransaction(); 
      _mapFragment = MapFragment.NewInstance(mapOptions); 
      fragTx.Add(Resource.Id.map, _mapFragment, "map"); 
      fragTx.Commit(); 
     } 
     _mapFragment.GetMapAsync(this); 
    } 

    public void OnMapReady(GoogleMap googleMap) 
    { 
     _map = googleMap; 
    } 
} 

Open MyMapActivity в вашем MainActivity:

private void Bt1_Click(object sender, System.EventArgs e) 
    { 
     StartActivity(typeof(MyMapActivity)); 
    } 

И это ваш фрагмент карты:

<?xml version="1.0" encoding="utf-8"?> 
<fragment xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/map" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    class="com.google.android.gms.maps.MapFragment" /> 

Снимок экрана:

GitHub source code

enter image description hereenter image description here

+0

Спасибо большое, он работает сейчас :) – eunal

+0

Так как я могу добавьте несколько маркеров и если это простое, местоположение? – eunal

+0

@eunal, пожалуйста, обратитесь к этому [demo] (https://developer.xamarin.com/samples/monodroid/MapsAndLocationDemo_v3/), это будет полезно –