我想在抽屉Layout
Fragment
内展示Google地图,我已经搜索了很多,但我无法找到一个好的解决方案。我面临的最后一个错误是:
MainActivity: Error in creating fragment
这样应用程序打开但显示了mo map。
我已将所有权限添加到清单中,如下所示:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.navigationdrawerexample"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="18" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="com.example.mapp1.permission.MAPS_RECEIVE"/>
<permission android:name="com.example.mapp1.permission.MAPS_RECEIVE" android:protectionLevel="signature" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.navigationdrawerexample.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyAan9QKDcqWXNfBeF0vUnoHui0itihkXww"/>
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
</application>
</manifest>
MapFragment.java看起来像:
public class MapFragment extends Fragment implements OnItemSelectedListener{
static final LatLng HAMBURG = new LatLng(32.333, 36.333) ;
static final LatLng KIEL = new LatLng(32.333, 35.333) ;
static final LatLng Home = new LatLng(31.333, 35.333) ;
AlertDialog.Builder ad;
GoogleMap map;
MapView mapView; // we should use it when we want a Map inside the fragment
private FragmentActivity fragmentActivity;
static int count=0;
private HashMap<Integer, Marker> WaypointsMarkers = new HashMap<Integer, Marker>();
Marker mr;
/*****/
private Fragment mVisible;
private SupportMapFragment mMapFragment;
private Fragment mFriendsFragment;
private GoogleMap mMap;
public MapFragment(){
}
@Override
public void onDestroyView() {
SupportMapFragment f = (SupportMapFragment) getFragmentManager()
.findFragmentById(R.id.map);
if (f != null) {
try {
getFragmentManager().beginTransaction().remove(f).commit();
} catch (Exception e) {
e.printStackTrace();
}
}
super.onDestroyView();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_map, container, false);
// View rootView = inflater.inflate(R.layout.fragment_data_flight, container, false);
/********************/
/****/
rootView = inflater.inflate(R.layout.fragment_map, container,false);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
SupportMapFragment supportMapFragment = (SupportMapFragment) fragmentManager
.findFragmentById(R.id.map);
map = supportMapFragment.getMap();
mapView = (MapView) rootView.findViewById(R.id.map);
mapView.onCreate(savedInstanceState);
if(mapView!=null)
{
map = mapView.getMap();
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
map.getUiSettings().setZoomControlsEnabled(true);
}
/*****^^^^^^^^^^^^^^^^^^***/
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
Context ctx=getActivity().getApplicationContext();
Button bt=(Button) getActivity().findViewById(R.id.button11);
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// WaypointsMarkers.get(1).remove();
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(WaypointsMarkers.get(1).getPosition()) // Sets the center of the map to Mountain View
.zoom(17) // Sets the zoom
.bearing(90) // Sets the orientation of the camera to east
.tilt(30) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
Fragment_Waypoint_info Fragwpt= new Fragment_Waypoint_info();
FragmentManager manger = getFragmentManager();
FragmentTransaction transaction = manger.beginTransaction();
transaction.add(R.id.main_layout, Fragwpt, "Fragwpt");
transaction.commit();
}
});
//Spinner
Spinner spinner = (Spinner) getActivity().findViewById(R.id.spinner1);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity().getApplicationContext(),
R.array.MapType, R.layout.spinner_item2);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
/***************************************************************/
}
// Convert a view to bitmap
public static Bitmap createDrawableFromView(Activity context, View view) {
DisplayMetrics displayMetrics = new DisplayMetrics();
((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
view.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
private void moveToCurrentLocation(LatLng currentLocation)
{
map.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLocation,20));
// Zoom in, animating the camera.
map.animateCamera(CameraUpdateFactory.zoomOut());
// Zoom out to zoom level 10, animating with a duration of 2 seconds.
map.animateCamera(CameraUpdateFactory.zoomTo(17), 3000, null);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
String MapType1= (String) parent.getItemAtPosition(position);
if (position==0)//(MapType1 == "MAP_TYPE_HYBRID")
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
else if (position==1)//(MapType1 == "MAP_TYPE_NONE")
map.setMapType(GoogleMap.MAP_TYPE_NONE);
else if (position==2)//(MapType1 == "MAP_TYPE_NORMAL")
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
else if (position==3)//(MapType1 == "MAP_TYPE_SATELLITE")
map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
else if (position==4)//(MapType1 == "MAP_TYPE_TERRAIN")
map.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
}// end of MapFragment
并且layout.xml是:
<fragment
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"/>
我做了以下修改: 1.在主要活动中添加一些行&#34; activity_main.xml&#34;
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
修改主要活动&#34; MainActvity.java&#34;
public class MainActivity extends FragmentActivity implements{
private GoogleMap mMap;
private SupportMapFragment fragment;
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private CharSequence mTitle;
private int batteryLevel = 2;
private int gpsLevel = 5;
private int rssiLevel = 2;
private MenuItem batteryItem;
private MenuItem gpsItem;
private MenuItem rssiItem;
private MenuItem connectItem;
/****/
private EditText et;
private Button b;
private int level1 = 1;
private int flag = 0;
int position = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mNavigationDrawerItemTitles = getResources().getStringArray(R.array.navigation_drawer_items_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
ObjectDrawerItem[] drawerItem = new ObjectDrawerItem[2];
drawerItem[0] = new ObjectDrawerItem(R.drawable.ic_flight_grey600_24dp, "Flight Data");
drawerItem[1] = new ObjectDrawerItem(R.drawable.ic_action_database, "Settings");
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.listview_item_row, drawerItem);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this,
mDrawerLayout,
R.drawable.ic_drawer,
R.string.drawer_open,
R.string.drawer_close
) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
if (savedInstanceState == null) {
selectItem(0);
}
}
private void setUpMapIfNeeded() {
if (mMap != null) {
return;
}
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
if (mMap == null) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
@Override
public void onMapClick(LatLng point) {
MarkerOptions marker = new MarkerOptions().position(
new LatLng(point.latitude, point.longitude)).title("New Marker");
mMap.addMarker(marker);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
batteryItem = menu.findItem(R.id.battery);
gpsItem = menu.findItem(R.id.gps);
rssiItem = menu.findItem(R.id.rssi);
connectItem = menu.findItem(R.id.connect);
}
private void selectItem(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new FlightDataFragment();
break;
case 1:
fragment = new SettingsFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).addToBackStack(null).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
}
以下是&#34; FlightDataFragment.java&#34;的代码。这是抽屉布局中的第一个片段,应该出现地图
public class FlightDataFragment extends Fragment{
static final LatLng HAMBURG = new LatLng(32.333, 36.333) ;
static final LatLng KIEL = new LatLng(32.333, 35.333) ;
static final LatLng Home = new LatLng(31.333, 35.333) ;
AlertDialog.Builder ad;
GoogleMap map;
MapView mapView;
private FragmentActivity fragmentActivity;
static int count=0;
private HashMap<Integer, Marker> WaypointsMarkers = new HashMap<Integer, Marker>();
Marker mr;
private Fragment mVisible;
private SupportMapFragment mMapFragment;
private Fragment mFriendsFragment;
private GoogleMap mMap;
private SeekBar seekBar2;
private EditText et
LinearLayout ArtificialHorizonLayout;
private static View rootView;
public FlightDataFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (rootView != null) {
ViewGroup parent = (ViewGroup) rootView.getParent();
if (parent != null)
parent.removeView(rootView);
}
try {
rootView = inflater.inflate(R.layout.fragment_data_flight, container, false);
} catch (InflateException e) {
}
ArtificialHorizonLayout = (LinearLayout) rootView.findViewById(R.id.ArtificialHorizonLayout);
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
SupportMapFragment supportMapFragment = (SupportMapFragment) fragmentManager.findFragmentById(R.id.map);
mapView = (MapView) rootView.findViewById(R.id.map);
mapView.onCreate(savedInstanceState);
map = supportMapFragment.getMap();
if(mapView!=null)
{
map = mapView.getMap();
map.getUiSettings().setMyLocationButtonEnabled(false);
map.setMyLocationEnabled(true);
map.getUiSettings().setZoomControlsEnabled(true);
}
if(map!=null)
{
Marker kiel= map.addMarker(new MarkerOptions()
.position(KIEL)
.title("Aircraft")
.snippet("Cool")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.airplane)));
Marker HomeMarker= map.addMarker(new MarkerOptions()
.position(Home)
.title("Home")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.home_3))
.alpha((float) .8)
);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(KIEL)
.zoom(25)
.bearing(90)
.tilt(30)
.build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
View marker = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker_layout, null);
TextView numTxt = (TextView) marker.findViewById(R.id.num_txt);
numTxt.setText("27");
Marker newmarker = map.addMarker(new MarkerOptions()
.position(HAMBURG)
.title("Title")
.snippet("Description")
.icon(BitmapDescriptorFactory.fromBitmap(MapFragment.createDrawableFromView(getActivity(), marker))));
map.setOnMapClickListener(new OnMapClickListener() {
@Override
public void onMapClick(LatLng arg0) {
count++;
View marker = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.custom_marker_layout, null);
TextView numTxt = (TextView) marker.findViewById(R.id.num_txt);
numTxt.setText(String.valueOf(count) );
Marker newmarker = map.addMarker(new MarkerOptions()
.position(arg0)
.title("Title")
.snippet(String.valueOf(count))
.icon(BitmapDescriptorFactory.fromBitmap(MapFragment.createDrawableFromView(getActivity(), marker))));
String Key1 = newmarker.getSnippet();
if (newmarker.getSnippet().equals("1"))
{
Toast.makeText(getActivity().getApplicationContext(), Key1,
Toast.LENGTH_LONG).show();
mr=newmarker;
}
if (!WaypointsMarkers.containsKey(count))
{
WaypointsMarkers.put(count, newmarker);
}
}
});
map.setOnMarkerClickListener(new OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker arg0) {
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(arg0.getPosition())
.zoom(30)
.bearing(90)
.tilt(30)
.build();
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
return false;
}
});
}
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ImageView compass = (ImageView) getActivity().findViewById(R.id.imageView12);
ImageView typesOfMaps = (ImageView) getActivity().findViewById(R.id.imageView22);
ImageView takeOff = (ImageView) getActivity().findViewById(R.id.imageView32);
ImageView gotoHome = (ImageView) getActivity().findViewById(R.id.imageView42);
ImageView follow = (ImageView) getActivity().findViewById(R.id.imageView52);
TextView uav_modes = (TextView) getActivity().findViewById(R.id.textView_uav_modes2);
final TextView agl_text = (TextView) getActivity().findViewById(R.id.agl_text);
seekBar2 = (SeekBar) getActivity().findViewById(R.id.seekBar2);
AttitudeIndicator attitudeIndicator = new AttitudeIndicator(getActivity().getApplicationContext());
ArtificialHorizonLayout.addView(attitudeIndicator);
final HorizontalScrollView scroll = (HorizontalScrollView) getActivity().findViewById(R.id.scroll12);
scroll.setVisibility(View.GONE);
}
它给出了&#34; FlightDataFragment.java&#34;中以下2行的错误:
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
SupportMapFragment supportMapFragment = (SupportMapFragment) fragmentManager.findFragmentById(R.id.map);
错误:
无法从Fragment转换为SupportMapFragment
我在网上尝试过没有有用结果的解决方案......任何帮助都将不胜感激
答案 0 :(得分:0)
您可以尝试代码here。并确保抽屉布局必须是布局文件中的根元素。
示例代码:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!-- google map -->
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"/>
</android.support.v4.widget.DrawerLayout>