Java 如何在映射片段中调用活动方法或整个活动

Java 如何在映射片段中调用活动方法或整个活动,java,android,google-maps,Java,Android,Google Maps,几天前,我开始了我的第一次编码体验。我的问题没有找到答案,所以我希望有人能帮助我 在我的项目中,我有一个main活动,带有底部导航视图,使用片段。我添加了一张地图作为片段之一,效果很好。 但是我在MapsActivity中更改并添加了一些方法,比如设备位置和请求许可。但当我运行应用程序时,它不会调用这些方法,所以我认为这是因为MapFragment需要获得MapsActivity的方法,但我不知道如何解决问题,也没有找到我问题的答案 我的地图碎片 public class Map_Fragmen

几天前,我开始了我的第一次编码体验。我的问题没有找到答案,所以我希望有人能帮助我

在我的项目中,我有一个
main活动
,带有
底部导航视图
,使用
片段
。我添加了一张地图作为片段之一,效果很好。 但是我在
MapsActivity
中更改并添加了一些方法,比如设备位置和请求许可。但当我运行应用程序时,它不会调用这些方法,所以我认为这是因为
MapFragment
需要获得
MapsActivity
的方法,但我不知道如何解决问题,也没有找到我问题的答案

我的地图碎片

public class Map_Fragment extends Fragment implements OnMapReadyCallback {

    SupportMapFragment mapFragment;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_map_, container, false);
        mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
        if (mapFragment == null) {
            FragmentManager fm = getFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            mapFragment = SupportMapFragment.newInstance();
            ft.replace(R.id.map, mapFragment).commit();

        }

        mapFragment.getMapAsync(this);
        
        // Inflate the layout for this fragment
        return v;
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {


    }
}
我的地图活动:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private static final String TAG = "MapActivity";
    private GoogleMap mMap;
    private static final String FINE_LOCATION = Manifest.permission.ACCESS_FINE_LOCATION;
    private static final String COARSE_LOCATION = Manifest.permission.ACCESS_COARSE_LOCATION;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1234;
    private static final float DEFAULT_ZOOM = 150f;
    // vars
    private Boolean mLocationPermissionGranted = false;

    private FusedLocationProviderClient mFusedLocationProviderClient;


    protected void createLocationRequest() {
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setInterval(10000);
        locationRequest.setFastestInterval(5000);
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }
    
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        Log.d(TAG, "onMapReady: Map is ready");

        if (mLocationPermissionGranted) {
            getDeviceLocation();
        }
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        Log.d(TAG, "onCreate: Map started");

        getLocationPermission();


    }

    private void getDeviceLocation() {
        Log.d(TAG, "getDeviceLocation : get the Devices current location");

        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        try {
            if (mLocationPermissionGranted) {
                Task location = mFusedLocationProviderClient.getLastLocation();
                location.addOnCompleteListener(new OnCompleteListener() {
                    @Override
                    public void onComplete(@NonNull Task task) {
                        if (task.isSuccessful()) {
                            Log.d(TAG, "onComplete: found location");
                            Location currentlocation = (Location) task.getResult();

                            moveCamera(new LatLng(currentlocation.getLatitude(), currentlocation.getLongitude()), DEFAULT_ZOOM);
                        } else {
                            Log.d(TAG, "onComplete: current Location is null");
                            Toast.makeText(MapsActivity.this, "unable to find location", Toast.LENGTH_SHORT);
                        }

                    }
                });
            }
        } catch (SecurityException e) {
            Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage());
        }

    }

    private void moveCamera(LatLng latLng, float zoom) {
        Log.d(TAG, "moveCamera: move the Camera to lat: " + latLng.latitude + ", lng" + latLng.longitude);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
    }

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    private void initMap() {
        Log.d(TAG, "Init Map");
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap googleMap) {
                mMap = googleMap;


            }
        });
    }

    private void getLocationPermission() {
        Log.d(TAG, "getLocationPermission");
        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};

        if (ContextCompat.checkSelfPermission(this.getApplicationContext(), FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            if (ContextCompat.checkSelfPermission(this.getApplicationContext(), COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                mLocationPermissionGranted = true;
                initMap();
            } else {

                ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
            }

        } else {
            ActivityCompat.requestPermissions(this, permissions, LOCATION_PERMISSION_REQUEST_CODE);
        }

    }

    public void onRequestPermissionResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grandResults) {
        Log.d(TAG, " onRequestPermissionResult: called");
        mLocationPermissionGranted = false;

        switch (requestCode) {
            case LOCATION_PERMISSION_REQUEST_CODE: {
                if (grandResults.length > 0) {
                    for (int i = 0; i < grandResults.length; i++) {
                        if (grandResults[i] == PackageManager.PERMISSION_GRANTED) {
                            mLocationPermissionGranted = false;
                            Log.d(TAG, "onRequestPermissionResult: failed");
                            return;
                        }
                    }
                    Log.d(TAG, "onRequestPermissionResult: Permission granted");
                    mLocationPermissionGranted = true;
                    //initialize our Map
                    initMap();
                }
            }
        }
    }


    /**
     * 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.
     */
}
公共类MapsActivity扩展了FragmentActivity在MapreadyCallback上的实现{
私有静态最终字符串TAG=“MapActivity”;
私有谷歌地图;
私有静态最终字符串FINE\u LOCATION=Manifest.permission.ACCESS\u FINE\u LOCATION;
私有静态最终字符串粗略\u位置=Manifest.permission.ACCESS\u粗略\u位置;
私有静态最终整数位置\权限\请求\代码=1234;
专用静态最终浮动默认值_缩放=150f;
//瓦尔斯
私有布尔值mlocationpermissiongrated=false;
私有FusedLocationProviderClient mFusedLocationProviderClient;
受保护的void createLocationRequest(){
LocationRequest LocationRequest=LocationRequest.create();
locationRequest.setInterval(10000);
locationRequest.SetFastTestInterval(5000);
locationRequest.setPriority(locationRequest.PRIORITY\u高精度);
}
@凌驾
4月1日公开作废(谷歌地图谷歌地图){
mMap=谷歌地图;
Log.d(标记“onMapReady:Map is ready”);
如果(已授予位置许可){
getDeviceLocation();
}
}
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_映射);
d(标记“onCreate:Map start”);
getLocationPermission();
}
私有void getDeviceLocation(){
Log.d(标记“getDeviceLocation:获取设备当前位置”);
mFusedLocationProviderClient=LocationServices.getFusedLocationProviderClient(此);
试一试{
如果(已授予位置许可){
任务位置=mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(新的OnCompleteListener(){
@凌驾
未完成的公共void(@NonNull任务){
if(task.issusccessful()){
Log.d(标记“onComplete:found location”);
Location currentlocation=(Location)task.getResult();
移动摄像机(新车床(currentlocation.getLatitude(),currentlocation.getLatitude()),默认为缩放);
}否则{
Log.d(标记“onComplete:当前位置为空”);
Toast.makeText(MapsActivity.this,“找不到位置”,Toast.LENGTH\u SHORT);
}
}
});
}
}捕获(安全异常e){
Log.e(标记“getDeviceLocation:SecurityException:”+e.getMessage());
}
}
专用移动摄影机(锁定、浮动变焦){
Log.d(标签,“移动摄像机:将摄像机移动到纬度:“+latLng.lation+”,lng“+latLng.longitude”);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,zoom));
}
//获取SupportMapFragment,并在地图准备好使用时收到通知。
私有void initMap(){
Log.d(标记“初始映射”);
SupportMapFragment mapFragment=(SupportMapFragment)getSupportFragmentManager()
.findFragmentById(R.id.map);
getMapAsync(新的OnMapReadyCallback(){
@凌驾
4月1日公开作废(谷歌地图谷歌地图){
mMap=谷歌地图;
}
});
}
私有void getLocationPermission(){
Log.d(标签“getLocationPermission”);
字符串[]权限={Manifest.permission.ACCESS\u FINE\u LOCATION,Manifest.permission.ACCESS\u rough\u LOCATION};
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),FINE_LOCATION)==PackageManager.PERMISSION_已授予){
if(ContextCompat.checkSelfPermission(this.getApplicationContext(),粗略位置)==PackageManager.PERMISSION\u已授予){
mLocationPermissionGratted=真;
initMap();
}否则{
ActivityCompat.requestPermissions(此、权限、位置\权限\请求\代码);
}
}否则{
ActivityCompat.requestPermissions(此、权限、位置\权限\请求\代码);
}
}
public void onRequestPermissionResult(int-requestCode、@NonNull字符串[]权限、@NonNull int[]grandResults){
d(标记“onRequestPermissionResult:called”);
mLocationPermissionGrassed=错误;
开关(请求代码){
案例位置\权限\请求\代码:{
如果(grandResults.length>0){
for(int i=0;ipublic class Map_Fragment extends Fragment {

    SupportMapFragment mapFragment;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

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

        View v = inflater.inflate(R.layout.fragment_map_,container, false);
        mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
        if (mapFragment==null){
            FragmentManager fm = getFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            mapFragment=SupportMapFragment.newInstance();
            ft.replace(R.id.map, mapFragment).commit();
        }

        Activity activity = getActivity();
        if (activity != null && activity instanceof MainActivity) {
            mapFragment.getMapAsync((MainActivity) activity);
        }

        // Inflate the layout for this fragment
        return v;
    }
}