java - 如何在地图片段中调用活动方法或整个活动
问题描述
几天前,我开始了我的第一次编码体验。没有找到我的问题的答案,所以我希望有人能帮助我。
在我的项目中,我有MainActivity
一个BottomNavigationView
using Fragments
。我添加了一张地图作为片段之一,它工作正常。但是我在 中更改并添加了一些方法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.
*/
}
MapFragment 使用 MapActivity 的方法如何将这两者相互连接?
解决方案
如果我正确理解您的问题,您希望OnMapReadyCallback
从活动而不是片段运行相关方法。如果是这种情况,您应该像这样修复您的片段:
public 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;
}
}
推荐阅读
- microsoft-graph-api - Microsoft Graph OneDrive API 在上传文件时返回 504 网关超时
- postgresql - 如何在此查询 postgresql 中获取 var cast 的值?
- php - 自动完成返回“0 个结果”
- string - 为什么翻译工作而不是 sed 换行
- sql-server - DELETE-OUTPUT-INTO 性能
- azure - 将服务主体客户端 ID 和机密传递给 ARM 模板
- python - Python elif 优化问题
- c# - 如何使用 iQueryable 返回一个空列
- python - 熊猫子集将不同的结果返回到 numpy
- python - 从包含很多列的大型 txt 数据文件中读取最后一列