我有标签活动,在第一个标签中我想显示地图片段。 我的问题是我不知道该怎么做。 我有扩展supportMapFragment的地图片段,但我仍然不知道如何在标签中显示该片段。
这是主要活动标签
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position) {
case 0:
// here i want to show the mapFragment. how should i do that?
return new Maps();
case 1:
return new GroupsFragment();
default:
return new Fragment();
}
}
修改 的 MapActivity
public class MapsActivity extends SupportMapFragment implements OnMapReadyCallback {
private static final int RC_LOCATION = 1;
private GoogleMap mMap;
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
addMyLocation();
}
private boolean checkLocationPermission(){
String[] permissions = new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION};
//If No Permission-> Request the permission and return false.
if (ActivityCompat.checkSelfPermission(getContext(),
android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), permissions, RC_LOCATION);
return false;
}
return true;//return true if we have a permission
}
private void addMyLocation(){
if (!checkLocationPermission())return;
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
@Override
public boolean onMyLocationButtonClick() {
if (mMap.getMyLocation()!=null) {
Location myLocation = mMap.getMyLocation();
Toast.makeText(getActivity(), "" + myLocation.getLatitude(), Toast.LENGTH_SHORT).show();
}
return false;
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
//noinspection MissingPermission
addMyLocation();
}
}
}
答案 0 :(得分:0)
试试这个
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
switch (position) {
case 0:
SupportMapFragment mapFragment = SupportMapFragment.newInstance();
mapFragment.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap googleMap) {
}
});
return mapFragment;
case 1:
return new GroupsFragment();
default:
return new Fragment();
}
}
@Override
public int getCount() {
return 3;
}
}