使用导航抽屉在片段和MapFragment之间切换

时间:2014-04-01 15:17:10

标签: android google-maps android-fragments navigation-drawer

我正在编写一个具有导航抽屉的应用程序。我希望其中一个片段中有一张地图。

我的MainActivity使用方法selectItem在framgents之间切换。

这是我的MainActivity.java

package de.illner.android.locationapi.maps;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends FragmentActivity {

    private String[]                mMenuTitles;
    private DrawerLayout            mDrawerLayout;
    private ListView                mDrawerList;
    private ActionBarDrawerToggle   mDrawerToggle;
    private CharSequence            mNavTitle;
    private CharSequence            mTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTitle = mNavTitle = getTitle();
        mMenuTitles = getResources().getStringArray(R.array.menu_entries);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

        // set up the drawer's list view with items and click listener
        mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mMenuTitles));
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        // enable ActionBar app icon to behave as action to toggle nav drawer
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(  this, /* host Activity */
                                                    mDrawerLayout, /* DrawerLayout object */
                                                    R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
                                                    R.string.drawer_open, /* "open drawer" description for accessibility */
                                                    R.string.drawer_close /* "close drawer" description for accessibility */
        ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mNavTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            selectItem(0);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // The action bar home/up action should open or close the drawer.
        // ActionBarDrawerToggle will take care of this.
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        else {
            return super.onOptionsItemSelected(item);
        }
    }

    /* The click listner for ListView in the navigation drawer */
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    }

    private void selectItem(int position) {
        // update the main content by replacing fragments
        Fragment fragment = null;

        //"Meine Aktuelle Position"
        if (position == 0)
        {
            fragment = new PositionFragment();
            Bundle args = new Bundle();
            args.putInt(PositionFragment.ARG_ENTRY_NUMBER, position);
            fragment.setArguments(args);
        }
        //"Melden (automatisch)" || "Melden (manuell)" || "Meine Meldungen verwalten"
        else if (position == 1 || position == 2 || position == 3)
        {
            fragment = new VerificationFragment();
            Bundle args = new Bundle();
            args.putInt(VerificationFragment.ARG_ENTRY_NUMBER, position);
            fragment.setArguments(args);
        }
        //"Meldungen zu Zeitpunkt"
        else if (position == 4)
        {

        }
        //"Über diese App"
        else if (position == 5)
        {

        }
        else
        {
            //position nicht in gültigem Bereich!
        }

        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        setTitle(mMenuTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }
}

这是带有NavigationDrawer的MainActivity的布局文件activity_main.xml

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#111"/>
</android.support.v4.widget.DrawerLayout>

这是我的地图碎片,应该从头开始。

PositionFragment.java

package de.illner.android.locationapi.maps;

import android.os.Bundle;
import android.support.v4.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.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;


public class PositionFragment extends Fragment {

    public static final String ARG_ENTRY_NUMBER = "entry_number";

    static final LatLng HAMBURG = new LatLng(53.558, 9.927);
    static final LatLng KIEL = new LatLng(53.551, 9.993);
    private GoogleMap map;

    public PositionFragment() {
        // Empty constructor required for fragment subclasses
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_position, container, false);
        int i = getArguments().getInt(ARG_ENTRY_NUMBER);
        String entryTitle = getResources().getStringArray(R.array.menu_entries)[i];
        getActivity().setTitle(entryTitle);


        map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
            Marker hamburg = map.addMarker(new MarkerOptions().position(HAMBURG)
                .title("Hamburg"));
            Marker kiel = map.addMarker(new MarkerOptions()
                .position(KIEL)
                .title("Kiel")
                .snippet("Kiel is cool")
                .icon(BitmapDescriptorFactory
                    .fromResource(R.drawable.ic_launcher)));

            // Move the camera instantly to hamburg with a zoom of 15.
            map.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));

            // Zoom in, animating the camera.
            map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);


        return rootView;
    }

    @Override
    public void onDestroyView() {

        SupportMapFragment f = (SupportMapFragment) getFragmentManager()
                .findFragmentById(R.id.content_frame);

        if (f != null) {
            try {
                getFragmentManager().beginTransaction().remove(f).commit();

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        super.onDestroyView();
    }
}

这里是必须在开头切换到的片段的布局: fragment_position.xml

<?xml version="1.0" encoding="utf-8"?>
<fragment
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.MapFragment" />

如果我想启动我的应用程序,我会在此行中获得NullPointerException:

map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

我认为问题出在activity_main.xmlfragment_position.xml

如果我想要启动另一个片段(没有地图),它会完美运行。

感谢所有人帮助我解决我可能的小故障;)

这是日志:

04-01 16:34:45.393: E/AndroidRuntime(3723): FATAL EXCEPTION: main
04-01 16:34:45.393: E/AndroidRuntime(3723): java.lang.RuntimeException: Unable to start activity ComponentInfo{de.illner.android.locationapi.maps/de.illner.android.locationapi.maps.MainActivity}: java.lang.NullPointerException
04-01 16:34:45.393: E/AndroidRuntime(3723):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2339)
04-01 16:34:45.393: E/AndroidRuntime(3723):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2389)
04-01 16:34:45.393: E/AndroidRuntime(3723):     at android.app.ActivityThread.access$600(ActivityThread.java:153)
04-01 16:34:45.393: E/AndroidRuntime(3723):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1269)
04-01 16:34:45.393: E/AndroidRuntime(3723):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-01 16:34:45.393: E/AndroidRuntime(3723):     at android.os.Looper.loop(Looper.java:137)
04-01 16:34:45.393: E/AndroidRuntime(3723):     at android.app.ActivityThread.main(ActivityThread.java:5289)
04-01 16:34:45.393: E/AndroidRuntime(3723):     at java.lang.reflect.Method.invokeNative(Native Method)
04-01 16:34:45.393: E/AndroidRuntime(3723):     at java.lang.reflect.Method.invoke(Method.java:525)
04-01 16:34:45.393: E/AndroidRuntime(3723):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
04-01 16:34:45.393: E/AndroidRuntime(3723):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:555)
04-01 16:34:45.393: E/AndroidRuntime(3723):     at dalvik.system.NativeStart.main(Native Method)
04-01 16:34:45.393: E/AndroidRuntime(3723): Caused by: java.lang.NullPointerException
04-01 16:34:45.393: E/AndroidRuntime(3723):     at de.illner.android.locationapi.maps.PositionFragment.onCreateView(PositionFragment.java:40)
04-01 16:34:45.393: E/AndroidRuntime(3723):     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
04-01 16:34:45.393: E/AndroidRuntime(3723):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
04-01 16:34:45.393: E/AndroidRuntime(3723):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
04-01 16:34:45.393: E/AndroidRuntime(3723):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
04-01 16:34:45.393: E/AndroidRuntime(3723):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
04-01 16:34:45.393: E/AndroidRuntime(3723):     at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:570)
04-01 16:34:45.393: E/AndroidRuntime(3723):     at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171)
04-01 16:34:45.393: E/AndroidRuntime(3723):     at android.app.Activity.performStart(Activity.java:5143)
04-01 16:34:45.393: E/AndroidRuntime(3723):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2302)
04-01 16:34:45.393: E/AndroidRuntime(3723):     ... 11 more

1 个答案:

答案 0 :(得分:0)

我有一个类似的问题,只需等待加载地图即可解决。它有时需要一些时间才能正确加载。尝试这样的事情:

Handler handler = new Handler();
handler.postDelayed(new Runnable() {

   @Override
   public void run() {
       // Get map as you do in your code
       if(map != null) {
         // Map loaded, precede as usual
       } else {
         // Keep delaying until the map is loaded.
         handler.postDelayed(this, 200);
       }
   }
}, 200);

希望这会有所帮助:)