我有一个带有两个标签的ViewPager,第一个是地方列表,第二个我想成为地方的地图。现在我可以从数据库填充列表,我让地图在应用程序的另一个地方工作,但是我无法使用标签布局作为片段。
这是我的地图片段的代码:
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
public class MapFragment extends Fragment implements OnInfoWindowClickListener,
LoaderManager.LoaderCallbacks<Cursor> {
MarkerOptions options = new MarkerOptions();
LatLngBounds.Builder build = new LatLngBounds.Builder();
GoogleMap map;
double[] lats;
double[] lngs;
String[] names;
String[] types;
int count;
int[] ids;
// @Override
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// View v = (RelativeLayout) inflater.inflate(R.layout.dialog_map,
// container, false);
// setUpMapIfNeeded(null, null);
// setupMarkers();
// LatLngBounds bounds = build.build();
// setUpMapIfNeeded(null, bounds);
// return v;
// }
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// setContentView(R.layout.dialog_map);
// setUpMapIfNeeded(null, null);
// Prepare the loader. Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, null, this);
}
private void setupMarkers() {
// get the passed crags names and locations
// double[] lats = getArguments().getDoubleArray(ClimbProvider.LAT);
// double[] lngs = getArguments().getDoubleArray(ClimbProvider.LONG);
// ArrayList<String> names = getArguments().getStringArrayList(
// ClimbProvider.NAME);
// interate and add every passed crag to the map as a marker
for (int i = 0; i < count; i++) {
// add the crags name and location to the marker
LatLng pos = new LatLng(lats[i], lngs[i]);
options.position(pos);
options.title((String) names[i]);
// add the marker to the map
map.addMarker(options);
map.setOnInfoWindowClickListener(this);
build.include(pos);
}
}
private void setUpMapIfNeeded(MarkerOptions options,
final LatLngBounds bounds) {
if (options == null && bounds == null) {
map = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
} else if (bounds != null) {
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
map.getUiSettings().setZoomControlsEnabled(false);
try {
map.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 70));
} catch (IllegalStateException e) {
// layout not yet initialised
final View mapView = getFragmentManager().findFragmentById(
R.id.map).getView();
if (mapView.getViewTreeObserver().isAlive()) {
mapView.getViewTreeObserver().addOnGlobalLayoutListener(
new OnGlobalLayoutListener() {
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
// We check which build version we are using.
@Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
mapView.getViewTreeObserver()
.removeGlobalOnLayoutListener(
this);
} else {
mapView.getViewTreeObserver()
.removeOnGlobalLayoutListener(
this);
}
map.moveCamera(CameraUpdateFactory
.newLatLngBounds(bounds, 70));
}
});
}
}
}
}
// when an info bubble is clicked get its title and search for it in the
// list of crag names the cross reference this with the list of crag ids and
// pass that to the view crag activity
@Override
public void onInfoWindowClick(Marker marker) {
int id = -1;
for (int i = 0; i < count; i++) {
if (names[i].contentEquals(marker.getTitle())) {
id = ids[i];
}
}
Intent viewCrag = new Intent(getActivity(), CragViewActivity.class);
viewCrag.putExtra("id", id);
Log.d("ClimbTrack", "row id = " + id);
startActivity(viewCrag);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// This is called when a new Loader needs to be created. This
// sample only has one Loader, so we don't care about the ID.
// First, pick the base URI to use depending on whether we are
// currently filtering.
Uri allcrags = Uri
.parse("content://com.fooforever.climbtrack.provider/crags");
return new CursorLoader(getActivity(), allcrags, null, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
ArrayList<Double> latsArray = new ArrayList<Double>();
ArrayList<Double> lngsArray = new ArrayList<Double>();
ArrayList<Integer> idsArray = new ArrayList<Integer>();
ArrayList<String> namesArray = new ArrayList<String>();
ArrayList<String> typesArray = new ArrayList<String>();
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
// mAdapter.swapCursor(data);
// move to the top of the query results
data.moveToFirst();
// put all the ids from the result into a list so they can be
// referenced against the listview item id
while (data.isAfterLast() == false) {
idsArray.add(data.getInt(data.getColumnIndex(ClimbProvider._ID)));
latsArray
.add(data.getDouble(data.getColumnIndex(ClimbProvider.LAT)));
lngsArray.add(data.getDouble(data
.getColumnIndex(ClimbProvider.LONG)));
namesArray.add(data.getString(data
.getColumnIndex(ClimbProvider.NAME)));
typesArray.add(data.getString(data
.getColumnIndex(ClimbProvider.TYPE)));
data.moveToNext();
}
count = data.getCount();
lats = new double[count];
lngs = new double[count];
names = new String[count];
types = new String[count];
ids = new int[count];
convert_arr_double(latsArray, lats);
convert_arr_double(lngsArray, lngs);
convert_arr_string(namesArray, names);
convert_arr_string(typesArray, types);
convert_arr_int(idsArray, ids);
// The list should now be shown.
// if (isResumed()) {
// setListShown(true);
// } else {
// setListShownNoAnimation(true);
// }
setupMarkers();
LatLngBounds bounds = build.build();
setUpMapIfNeeded(null, bounds);
}
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
// TODO
}
// convert the passed arraylist to a double array
private void convert_arr_double(ArrayList<Double> array, double[] out) {
for (int i = 0; i < count; i++) {
out[i] = array.get(i);
}
}
private void convert_arr_string(ArrayList<String> array, String[] out) {
for (int i = 0; i < count; i++) {
out[i] = array.get(i);
}
}
private void convert_arr_int(ArrayList<Integer> array, int[] out) {
for (int i = 0; i < count; i++) {
out[i] = array.get(i);
}
}
}
我在setupmapifneeded()函数中初始化地图时遇到编译错误。
The method getMap() is undefined for the type MapFragment
在第88行4/5行的setupmap ifneeded()函数。
我无法弄清楚为什么我在这里遇到编译错误,这是实现此类功能的最佳方法吗?
答案 0 :(得分:2)
使用ViewPager
在列表和地图之间导航可能会产生一些令人沮丧的行为 - 尝试平移地图可能会导致切换视图,反之亦然。
您可以使用普通标签导航(删除任何平移/视图切换挫折),也可以为地图视图实施“锁定”按钮以锁定平移。
至于为什么会出现编译错误:
public class MapFragment extends Fragment implements OnInfoWindowClickListener,
LoaderManager.LoaderCallbacks<Cursor> {
...
map = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
}
您正在使用错误类型 MapFragment
。重命名您的 MapFragment
(例如,AppNameMapFragment
)或完全限定演员:
您之前尝试从Fragment
投射 MapFragment
。在我之前的回答中,我错过了你也在使用支持库。因此,您需要使用getSupportFragmentManager
,并且需要转换为SupportMapFragment
:
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(
R.id.map)).getMap();