按钮点击后在片段中显示地图

时间:2017-11-30 08:45:56

标签: android google-maps android-fragments

我正在尝试在Android项目中使用Google Map。一个人的详细信息将连续显示,并且点击一个按钮,将使用针对该人保存的纬度和经度显示该位置。我正在使用片段进行显示。

activity_show_map.xml

<?xml version="1.0" encoding="utf-8"?>

<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.dioglgt.myapplication.ClinicFragment" />

下面给出了相应的ClinicFragment java类:

public class ClinicFragment extends Fragment implements OnMapReadyCallback {

private GoogleMap mMap;
public static ClinicFragment newInstance() {
    ClinicFragment fragment = new ClinicFragment();
    return fragment;
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.activity_show_map, null, false);

    SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    return view;
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    LatLng testLocation = new LatLng(93.972, 26.515);
    mMap.addMarker(new MarkerOptions().position(testLocation).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(testLocation));
}
}

现在要在点击按钮时触发地图显示,我使用下面的代码:

  public void onShowLocationClick(View view) {
    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.add(R.id.map,new ClinicFragment());
    transaction.addToBackStack(null);
    transaction.commit();
}

但我收到错误:

java.lang.IllegalArgumentException: No view found for id 0x7f0e0087 (com.example.dioglgt.myapplication:id/map) for fragment ClinicFragment{9dd7da #0 id=0x7f0e0087}

请在这方面提供指导。

2 个答案:

答案 0 :(得分:1)

必须使用此

 public void onShowLocationClick(View view) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.add(android.R.id.content,new ClinicFragment());
        transaction.addToBackStack(null);
        transaction.commit();
    }

答案 1 :(得分:0)

您正尝试在ID为map的片段上添加ClinicFragment,其内部为activity_show_map,设置为Clinic片段。尝试使用frameLayout并将该frameLayout替换为下面按钮点击链接上的片段:

Fragmentmanager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.fragment_container, new ClinicFragment()).commit();

在上面的代码中fragment_container是一个FrameLayout,它将替换为ClinicFragment;

相关问题