Android 在选项卡式Fragement中获取我的当前位置
我有三个可开关的标签。每个选项卡都是一个片段。第一个片段显示一个图像。第二个片段用于获取用户的位置并将其显示在地图上。我在第二个片段的布局中使用了SupportMapFragment,请参见下面的xml:fragement_map.xmlAndroid 在选项卡式Fragement中获取我的当前位置,android,location,android-location,gmsmapview,Android,Location,Android Location,Gmsmapview,我有三个可开关的标签。每个选项卡都是一个片段。第一个片段显示一个图像。第二个片段用于获取用户的位置并将其显示在地图上。我在第二个片段的布局中使用了SupportMapFragment,请参见下面的xml:fragement_map.xml <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.an
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/current_location"
android:name="com.google.android.gms.maps.SupportMapFragment"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="?attr/actionBarSize"
/>
</android.support.constraint.ConstraintLayout>
保存片段代码的活动如下所示:
public class TabActivity extends AppCompatActivity {
private TabLayout tabLayout;
//This is our viewPager
private ViewPager viewPager;
String[] tabTitle={"Image","Your Location","Sign Out"};
ImageFragment imageFragment;
MapFragment mapFragment;
LogOutFragment logOutFragment;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab);
//Initializing viewPager
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setOffscreenPageLimit(3);
setupViewPager(viewPager);
//Initializing the tablayout
tabLayout = (TabLayout) findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
viewPager.setCurrentItem(position,false);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
}
private void setupViewPager(ViewPager viewPager) {
if(activeNetwork())
{
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
imageFragment = new ImageFragment();
mapFragment = new MapFragment();
logOutFragment = new LogOutFragment();
adapter.addFragment(imageFragment, "Image");
adapter.addFragment(mapFragment, "Map");
adapter.addFragment(logOutFragment, "Logout");
viewPager.setAdapter(adapter);
}
else
{
}
}
public boolean activeNetwork () {
// TODO: Not the most efficient method but will do for this context
ConnectivityManager cm =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnected();
return isConnected;
}
}
我目前面临的问题是地图显示。但是,Google OnMyLocationButtonClickListener按钮不会显示,下面的当前视图也会显示,我的当前位置也不会显示
我希望地图显示如下图所示我最终解决了问题,请参见下面的代码:
public class MapFragment extends Fragment implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener
{
private View view;
SupportMapFragment supportMapFragment;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
GoogleMap mGoogleMap;
public static final int PERMISSIONS_REQUEST_LOCATION = 100;
private Toolbar toolbar;
public MapFragment()
{
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.fragment_map, container, false);
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
init();
}
private void init() {
toolbar = view.findViewById(R.id.toolbar);
toolbar.setTitle("Your Location");
toolbar.setTitleTextColor(Color.WHITE);
supportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(this);
}
@Override
public void onConnected(@Nullable Bundle bundle)
{
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this.getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
@Override
public void onConnectionSuspended(int i)
{
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult)
{
}
@Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(this.getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED)
{
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else
{
//Request Location Permission to user
checkPermission();
}
} else
{
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
private void checkPermission()
{
if (ContextCompat.checkSelfPermission(this.getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this.getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION))
{
new AlertDialog.Builder(this.getActivity())
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialogInterface, int i)
{
ActivityCompat.requestPermissions(MapFragment.this.getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
} else
{
ActivityCompat.requestPermissions(this.getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_LOCATION);
}
}
}
protected synchronized void buildGoogleApiClient()
{
mGoogleApiClient = new GoogleApiClient.Builder(this.getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
switch (requestCode)
{
case PERMISSIONS_REQUEST_LOCATION:
{
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
if (ContextCompat.checkSelfPermission(this.getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED)
{
if (mGoogleApiClient == null)
{
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else
{
Toast.makeText(this.getActivity(), "permission denied by user", Toast.LENGTH_LONG).show();
}
return;
}
}
}
@Override
public void onPause()
{
super.onPause();
if (mGoogleApiClient != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
@Override
public void onLocationChanged(Location location)
{
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
//move map camera and we can also set zoom level
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,15));
}
public class MapFragment extends Fragment implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
com.google.android.gms.location.LocationListener
{
private View view;
SupportMapFragment supportMapFragment;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
GoogleMap mGoogleMap;
public static final int PERMISSIONS_REQUEST_LOCATION = 100;
private Toolbar toolbar;
public MapFragment()
{
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
view = inflater.inflate(R.layout.fragment_map, container, false);
return view;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
init();
}
private void init() {
toolbar = view.findViewById(R.id.toolbar);
toolbar.setTitle("Your Location");
toolbar.setTitleTextColor(Color.WHITE);
supportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
supportMapFragment.getMapAsync(this);
}
@Override
public void onConnected(@Nullable Bundle bundle)
{
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this.getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED)
{
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
@Override
public void onConnectionSuspended(int i)
{
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult)
{
}
@Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(this.getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED)
{
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
} else
{
//Request Location Permission to user
checkPermission();
}
} else
{
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
private void checkPermission()
{
if (ContextCompat.checkSelfPermission(this.getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(this.getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION))
{
new AlertDialog.Builder(this.getActivity())
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialogInterface, int i)
{
ActivityCompat.requestPermissions(MapFragment.this.getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
} else
{
ActivityCompat.requestPermissions(this.getActivity(),
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_LOCATION);
}
}
}
protected synchronized void buildGoogleApiClient()
{
mGoogleApiClient = new GoogleApiClient.Builder(this.getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
switch (requestCode)
{
case PERMISSIONS_REQUEST_LOCATION:
{
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
if (ContextCompat.checkSelfPermission(this.getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED)
{
if (mGoogleApiClient == null)
{
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
} else
{
Toast.makeText(this.getActivity(), "permission denied by user", Toast.LENGTH_LONG).show();
}
return;
}
}
}
@Override
public void onPause()
{
super.onPause();
if (mGoogleApiClient != null)
{
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
}
@Override
public void onLocationChanged(Location location)
{
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
//move map camera and we can also set zoom level
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,15));
}