Playストアで同じタブレイアウトを作成しようとしています。androidhiveのフラグメントとビューページャーを使用してタブレイアウトを表示する必要があります。ただし、Google Maps v2を実装することはできません。すでに何時間もインターネットを検索しましたが、その方法に関するチュートリアルが見つかりません。誰か教えてください。
ActivityとFragment以前getChildFragmentManager()に使用した場合の違いはあまりありません。
                Playストアで同じタブレイアウトを作成しようとしています。androidhiveのフラグメントとビューページャーを使用してタブレイアウトを表示する必要があります。ただし、Google Maps v2を実装することはできません。すでに何時間もインターネットを検索しましたが、その方法に関するチュートリアルが見つかりません。誰か教えてください。
ActivityとFragment以前getChildFragmentManager()に使用した場合の違いはあまりありません。
                回答:
このコードを使用することで、任意のViewPagerまたはFragmentまたはActivity内のどこにでもMapViewを設定できます。
Google for Mapsの最新アップデートでは、フラグメントに対してMapViewのみがサポートされています。MapFragment&SupportMapFragmentが機能しません。私は間違っているかもしれませんが、これはMapFragment&SupportMapFragmentを実装しようとした後に見たものです。
ファイルにマップを表示するためのレイアウトを設定しますlocation_fragment.xml。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <com.google.android.gms.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>次に、ファイルにマップを表示するためのJavaクラスをコーディングしますMapViewFragment.java。
public class MapViewFragment extends Fragment {
    MapView mMapView;
    private GoogleMap googleMap;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.location_fragment, container, false);
        mMapView = (MapView) rootView.findViewById(R.id.mapView);
        mMapView.onCreate(savedInstanceState);
        mMapView.onResume(); // needed to get the map to display immediately
        try {
            MapsInitializer.initialize(getActivity().getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
        mMapView.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap mMap) {
                googleMap = mMap;
                // For showing a move to my location button
                googleMap.setMyLocationEnabled(true);
                // For dropping a marker at a point on the Map
                LatLng sydney = new LatLng(-34, 151);
                googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));
                // For zooming automatically to the location of the marker
                CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
                googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            }
        });
        return rootView;
    }
    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }
    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
    }
    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }
}最後に、Google Cloud Consoleにアプリを登録して、アプリのAPIキーを取得する必要があります。アプリをネイティブAndroidアプリとして登録します。
<uses-library android:name="com.google.android.maps" android:required="true" />Maps V2ではなく、Maps V1用です。com.google.android.mapsファームウェアライブラリを持たないが、Maps V2マップを完全に表示できるデバイスが将来的に存在するでしょう。マニフェストにこの行があると、そのようなデバイスで実行できなくなります。この行は、Maps V2の使用には必要ありません。たとえば、github.com / commonsguy / cw-omnibus / tree / master / MapsV2にある17個のプロジェクトにはこの<uses-library>要素がなく、正常に動作します。
                    java.lang.NullPointerException: Attempt to invoke interface method 'void com.google.maps.api.android.lib6.impl.bo.o()' on a null object reference
                    次のアプローチは私のために働きます。
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
/**
 * A fragment that launches other parts of the demo application.
 */
public class MapFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // inflat and return the layout
    View v = inflater.inflate(R.layout.fragment_location_info, container,
            false);
    mMapView = (MapView) v.findViewById(R.id.mapView);
    mMapView.onCreate(savedInstanceState);
    mMapView.onResume();// needed to get the map to display immediately
    try {
        MapsInitializer.initialize(getActivity().getApplicationContext());
    } catch (Exception e) {
        e.printStackTrace();
    }
    googleMap = mMapView.getMap();
    // latitude and longitude
    double latitude = 17.385044;
    double longitude = 78.486671;
    // create marker
    MarkerOptions marker = new MarkerOptions().position(
            new LatLng(latitude, longitude)).title("Hello Maps");
    // Changing marker icon
    marker.icon(BitmapDescriptorFactory
            .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
    // adding marker
    googleMap.addMarker(marker);
    CameraPosition cameraPosition = new CameraPosition.Builder()
            .target(new LatLng(17.385044, 78.486671)).zoom(12).build();
    googleMap.animateCamera(CameraUpdateFactory
            .newCameraPosition(cameraPosition));
    // Perform any camera updates here
    return v;
}
@Override
public void onResume() {
    super.onResume();
    mMapView.onResume();
}
@Override
public void onPause() {
    super.onPause();
    mMapView.onPause();
}
@Override
public void onDestroy() {
    super.onDestroy();
    mMapView.onDestroy();
}
@Override
public void onLowMemory() {
    super.onLowMemory();
    mMapView.onLowMemory();
}
}fragment_location_info.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.gms.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />java.lang.NullPointerException: IBitmapDescriptorFactory is not initialized。トライキャッチならこれで大丈夫だと思いました。誰かが私を助けてくれますか?
                    mMapViewか?
                    getMap()廃止予定です。代わりにgetMapAsyncとonMapReadyCallbackを使用してください:stackoverflow.com/a/31371953/4549776
                    GoogleMapフラグメントで使用したい場合は、次の行を使用できます。
<fragment
            android:id="@+id/map"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            class="com.google.android.gms.maps.SupportMapFragment" />GoogleMap mGoogleMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)).getMap();getMapAsync非推奨のものの代わりに最新のもの。
1.マニフェストをチェック
<meta-data android:name="com.google.android.geo.API_KEY" android:value="xxxxxxxxxxxxxxxxxxxxxxxxx"/>でアプリを登録することにより、アプリのAPIキーを取得できますGoogle Cloud Console。アプリをネイティブAndroidアプリとして登録する
2.フラグメントレイアウト.xmlにFrameLayout(フラグメントではない)を追加します。
                  <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="250dp"
                android:layout_weight="2"
                android:name="com.google.android.gms.maps.SupportMapFragment"
                android:id="@+id/mapwhere" />またはあなたが望むどんな高さでも
3.フラグメントのonCreateViewで
    private SupportMapFragment mSupportMapFragment; 
    mSupportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapwhere);
    if (mSupportMapFragment == null) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        mSupportMapFragment = SupportMapFragment.newInstance();
        fragmentTransaction.replace(R.id.mapwhere, mSupportMapFragment).commit();
    }
    if (mSupportMapFragment != null)
    {
        mSupportMapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override public void onMapReady(GoogleMap googleMap) {
                if (googleMap != null) {
                    googleMap.getUiSettings().setAllGesturesEnabled(true);
                      -> marker_latlng // MAKE THIS WHATEVER YOU WANT
                        CameraPosition cameraPosition = new CameraPosition.Builder().target(marker_latlng).zoom(15.0f).build();
                        CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
                        googleMap.moveCamera(cameraUpdate);
                }
            }
        });<fragment代わりにあるべきですFrameLayout
                    SupportMapFragmentにMapFragment活性が、変更FrameLayoutにfragmentレイアウトファイルと、変更com.google.android.gms.maps.SupportMapFragmentにcom.google.android.gms.maps.MapFragment、それは私のために罰金を動作します。これらの変更の前は機能しませんでした。たぶんこれは他の人を助ける....
                    ここで私が詳細にしたこと:
別の簡単な方法
最初にGoogleアカウントにログインし、Googleライブラリにアクセスして、Google Maps Android APIを選択します
Android Studioのデフォルトのマップアクティビティに依存関係が見つかりました:
compile 'com.google.android.gms:play-services:10.0.1'以下のようなアプリケーションの下にあるAndroidのメインファイルにキーを入れてください
AndroidMainifest.xmlで次の変更を行います。
    // required permission
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        // google map api key put under/inside <application></application>
        // android:value="YOUR API KEY"
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzasdfasdf645asd4f847sad5f45asdf7845" />フラグメントコード:
public class MainBranchFragment extends Fragment implements OnMapReadyCallback{
private GoogleMap mMap;
    public MainBranchFragment() {
        // Required empty public constructor
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.fragment_main_branch, container, false);
        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.main_branch_map);
        mapFragment.getMapAsync(this);
        return view;
    }
     @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
            LatLng UCA = new LatLng(-34, 151);
            mMap.addMarker(new MarkerOptions().position(UCA).title("YOUR TITLE")).showInfoWindow();
            mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(UCA,17));
        }
    }あなたのフラグメントxml:
<fragment
                android:id="@+id/main_branch_map"
                android:name="com.google.android.gms.maps.SupportMapFragment"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context="com.googlemap.googlemap.MapsActivity" />でNullPointerExceptionタブを変更するときにaを取得する問題についてはFragmentTabHost、を含むクラスにこのコードを追加するだけですTabHost。つまり、タブを初期化するクラスです。これはコードです:
/**** Fix for error : Activity has been destroyed, when using Nested tabs 
 * We are actually detaching this tab fragment from the `ChildFragmentManager`
 * so that when this inner tab is viewed back then the fragment is attached again****/
import java.lang.reflect.Field;
@Override
public void onDetach() {
    super.onDetach();
    try {
        Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
        childFragmentManager.setAccessible(true);
        childFragmentManager.set(this, null);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}public class DemoFragment extends Fragment {
MapView mapView;
GoogleMap map;
LatLng CENTER = null;
public LocationManager locationManager;
double longitudeDouble;
double latitudeDouble;
String snippet;
String title;
Location location;
String myAddress;
String LocationId;
String CityName;
String imageURL;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View view = inflater
                .inflate(R.layout.fragment_layout, container, false);
    mapView = (MapView) view.findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
  setMapView();
 }
 private void setMapView() {
    try {
        MapsInitializer.initialize(getActivity());
        switch (GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(getActivity())) {
        case ConnectionResult.SUCCESS:
            // Toast.makeText(getActivity(), "SUCCESS", Toast.LENGTH_SHORT)
            // .show();
            // Gets to GoogleMap from the MapView and does initialization
            // stuff
            if (mapView != null) {
                locationManager = ((LocationManager) getActivity()
                        .getSystemService(Context.LOCATION_SERVICE));
                Boolean localBoolean = Boolean.valueOf(locationManager
                        .isProviderEnabled("network"));
                if (localBoolean.booleanValue()) {
                    CENTER = new LatLng(latitude, longitude);
                } else {
                }
                map = mapView.getMap();
                if (map == null) {
                    Log.d("", "Map Fragment Not Found or no Map in it!!");
                }
                map.clear();
                try {
                    map.addMarker(new MarkerOptions().position(CENTER)
                            .title(CityName).snippet(""));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                map.setIndoorEnabled(true);
                map.setMyLocationEnabled(true);
                map.moveCamera(CameraUpdateFactory.zoomTo(5));
                if (CENTER != null) {
                    map.animateCamera(
                            CameraUpdateFactory.newLatLng(CENTER), 1750,
                            null);
                }
                // add circle
                CircleOptions circle = new CircleOptions();
                circle.center(CENTER).fillColor(Color.BLUE).radius(10);
                map.addCircle(circle);
                map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            }
            break;
        case ConnectionResult.SERVICE_MISSING:
            break;
        case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:
            break;
        default:
        }
    } catch (Exception e) {
    }
}fragment_layout内
<com.google.android.gms.maps.MapView
                android:id="@+id/mapView"
                android:layout_width="match_parent"
                android:layout_height="160dp"                    
                android:layout_marginRight="10dp" />マップを追加する場合は、以下を使用します。
getChildFragmentManager().beginTransaction()
    .replace(R.id.menu_map_container, mapFragment, "f" + shabbatIndex).commit();の代わりに.add、代わりにgetFragmentManager。
MapActivityを作成し、それをフラグメントに拡張します。MapActivity.java:
package com.example.ahmedsamra.mansouratourguideapp;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
    private GoogleMap mMap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_categories);//layout for container
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, new MapFragment())
                .commit();
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        // Add a marker in Sydney and move the camera
        LatLng mansoura = new LatLng(31.037933, 31.381523);
        mMap.addMarker(new MarkerOptions().position(mansoura).title("Marker in mansoura"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(mansoura));
    }
}activity_map.xml:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.ahmedsamra.mansouratourguideapp.MapsActivity" />MapFragment.java:-
package com.example.ahmedsamra.mansouratourguideapp;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
 * A simple {@link Fragment} subclass.
 */
public class MapFragment extends Fragment {
    public MapFragment() {
        // Required empty public constructor
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.activity_maps,container,false);
        return rootView;
    }
}NullPointerExceptionフラグメントをオンに削除するときの回避策DestoryViewがあります。コードを入れonStop()ないでくださいonDestoryView。うまくいきます!
@Override
public void onStop() {
    super.onStop();
    if (mMap != null) {
        MainActivity.fragmentManager.beginTransaction()
                .remove(MainActivity.fragmentManager.findFragmentById(R.id.location_map)).commit();
        mMap = null;
    }
}https://developer.android.com/about/versions/android-4.2.html#NestedFragmentsによると、ネストされたフラグメントを使用してこれを達成するには、getChildFragmentManager()を呼び出して、自分のフラグメント内を見る:
SupportMapFragment mapFragment = new SupportMapFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.content, mapFragment).commit();ここで、「コンテンツ」はフラグメント(できればFrameLayout)のルートレイアウトです。マップフラグメントを使用する利点は、マップライフサイクルがシステムによって自動的に管理されることです。
ドキュメントには、「レイアウトに<fragment>が含まれている場合、レイアウトをフラグメントにインフレートすることはできません。ネストされたフラグメントは、フラグメントに動的に追加された場合にのみサポートされます。」と記載されていますが、私は何らかの方法でこれを正常に実行し、正常に機能しました。これが私のコードです:
フラグメントのonCreateView()メソッドで:
View view = inflater.inflate(R.layout.layout_maps, container, false);
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(...);レイアウトでは:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />それが役に立てば幸い!
マップフラグメントを動的に追加してページャーを表示する:
APIレベル12より前のアプリケーションを対象としている場合は、SupportedMapFragmentのインスタンスを作成し、それをビューページアダプターに追加します。
SupportMapFragment supportMapFragment=SupportMapFragment.newInstance();
        supportMapFragment.getMapAsync(this);APIレベル12以上でMapFragmentオブジェクトをサポート
MapFragment mMapFragment=MapFragment.newInstance();
            mMapFragment.getMapAsync(this);これはKotlinの方法です。
ではfragment_map.xml、あなたが持っている必要があります。
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />あなたの中でMapFragment.kt:
    private fun setupMap() {
        (childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment?)!!.getMapAsync(this)
    }に電話setupMap()してくださいonCreateView。