我正在开发一个在片段上显示地图的应用程序。一切都准备好了,但是有一点小事情让我无法完成。
gMapFragment.java:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class gMapFragment extends Fragment implements OnMapReadyCallback {
public gMapFragment() {
// Required empty public constructor
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_map, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
MapFragment fragment = (MapFragment) getChildFragmentManager().findFragmentById(R.id.map);
fragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
LatLng marker = new LatLng(46.33328, 15.38173);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(marker,13));
googleMap.addMarker(new MarkerOptions().title(("HERE WE ARE!")).position(marker));
}
}
我从另一个frament中的button调用此片段,这是调用它的方法:
public void onClick(View view) {
Fragment fragment = null;
switch (view.getId()) {
case R.id.SearchButton:
fragment = new gMapFragment();
replaceFragment(fragment);
break;
}
}
public void replaceFragment(Fragment someFragment) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, someFragment);
transaction.addToBackStack(null);
transaction.commit();
}
我收到错误消息“ gMapFragment无法转换为片段”。如何解决此问题?谢谢!
最佳答案
首先,请确保您与Fragment导入一致。在所有类中使用import android.app.Fragment
或在所有类中使用import android.support.v4.app.Fragment;
。不要混搭。
然后,将其添加到“活动”中:
public void openMapFragment() {
Fragment fragment = new gMapFragment();
replaceFragment(fragment);
}
//moved to Activity from the Fragment
public void replaceFragment(Fragment someFragment) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, someFragment);
transaction.addToBackStack(null);
transaction.commit();
}
然后,在Fragment
onClick()
方法中,只需调用Activity来执行FragmentTransaction:public void onClick(View view) {
switch (view.getId()) {
case R.id.SearchButton:
MainActivity activity = (MainActivity) getActivity();
if (activity != null) {
activity.openMapFragment();
}
break;
}
}