当前位置: 代码迷 >> java >> 带导航抽屉的MapFragment
  详细解决方案

带导航抽屉的MapFragment

热度:92   发布时间:2023-08-02 10:41:30.0

我正在按照本教程制作导航抽屉:

我的片段之一是定义如下的地图:

XML格式

<fragment  android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    class="com.google.android.gms.maps.MapFragment" />

    <FrameLayout android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
        /*Some texts and buttons */
    </FrameLayout>
</RelativeLayout>

爪哇

public class MapsFragment extends Fragment implements AsyncResponse {

    private View mView;
    private GoogleMap mMap;
    private LayoutInflater mInflater;
    private Bundle savedInstanceState;
    private CustomButton mCancelButton;
    private CustomButton mPeekButton;
    private boolean mActivityPaused;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    mPeeks = new ArrayList();
    mGson = new Gson();
    mInflater = inflater;
    mIsPaneOpen = false;
    mMarkerMap = new HashMap();

    if (mView != null) {
        ViewGroup parent = (ViewGroup) mView.getParent();
        if (parent != null)
            parent.removeView(mView);
        }
        try {
            mView =  mInflater.inflate(R.layout.activity_maps, container, false);
        } catch (InflateException e) {
            e.printStackTrace();
        }


        setUpMapIfNeeded();

        mCancelButton = (CustomButton) mView.findViewById(R.id.bt_cancel);
        return mView;

    }

    public void setUpMapIfNeeded(){
        if (mMap == null){
            mMap = ((MapFragment) getActivity().getFragmentManager().findFragmentById(R.id.map)).getMap();
            if (mMap != null)
                setUpMap();
        }
    }

    private void setUpMap() {
        mMap.setMyLocationEnabled(true);
        //Some code
    }
}

我自愿删除了一些不相关的代码。 然后我有主要活动:

XML格式

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

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

        <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

            <!-- The ActionBar -->
            <include
                    layout="@layout/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content" />

            <!-- The main content view -->
            <FrameLayout
                    android:id="@+id/flContent"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />
        </LinearLayout>

        <!-- The navigation drawer -->
        <android.support.design.widget.NavigationView
                android:id="@+id/nvView"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_gravity="start"
                android:background="@android:color/white"
                app:menu="@menu/drawer_view" />
    </android.support.v4.widget.DrawerLayout>
</LinearLayout>

爪哇

public class MainActivity extends AppCompatActivity {

    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */
    //Manager de Fragment
    DrawerLayout mDrawer;                                  // Declaring DrawerLayout
    Toolbar mToolbar;
    Fragment currentFrag;
    FragmentManager mFragmentManager;
    Fragment mMapFragment;
    Fragment mUserFragment;
    Fragment mThirdFragment;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mFragmentManager =  getSupportFragmentManager();


        mMapFragment = new MapsFragment();
        mUserFragment = new UserFragment();
        mThirdFragment = new ThirdFragment();
        //Initializing the first Fragment
        mFragmentManager.beginTransaction().replace(R.id.flContent, new MapsFragment()).commit();

        // Set a Toolbar to replace the ActionBar.
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);

        // Find our drawer view
        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);

        // Set the menu icon instead of the launcher icon.
        final ActionBar ab = getSupportActionBar();
        ab.setHomeAsUpIndicator(R.drawable.ic_menu);
        ab.setDisplayHomeAsUpEnabled(true);
        // Find our drawer view
        NavigationView nvDrawer = (NavigationView) findViewById(R.id.nvView);
        // Setup drawer view
        setupDrawerContent(nvDrawer);
    }

    //First We Declare Titles And Icons For Our Navigation Drawer List View
    //This Icons And Titles Are holded in an Array as you can see

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // The action bar home/up action should open or close the drawer.
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawer.openDrawer(GravityCompat.START);
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
    }
    private void setupDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        selectDrawerItem(menuItem);
                        return true;
                    }
                });
    }

    public void selectDrawerItem(MenuItem menuItem) {
        // Create a new fragment and specify the planet to show based on
        // position

        Fragment fragment = null;
        switch(menuItem.getItemId()) {
            case R.id.nav_map:
                fragment = mMapFragment;
                break;
            case R.id.nav_profile:
                fragment = mUserFragment;
                break;
            case R.id.nav_nav_settings:
                fragment = mThirdFragment;
                break;
            default:
                fragment = mMapFragment;
        }

        // Insert the fragment by replacing any existing fragment

        mFragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();


        // Highlight the selected item, update the title, and close the drawer
        menuItem.setChecked(true);
        setTitle(menuItem.getTitle());
        mDrawer.closeDrawers();
    }


}

问题是,当我第一次附加de MapFragment时,没问题,活动将显示地图。 但是,当我尝试通过导航抽屉转到另一个片段,然后又回到地图片段时,我遇到了以下异常:

07-19 16:04:25.710  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ android.view.InflateException: Binary XML file line #12: Error inflating class fragment
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:770)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.view.LayoutInflater.inflate(LayoutInflater.java:511)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at fr.yougraph.homelesspasseul.fragment.MapsFragment.onCreateView(MapsFragment.java:93)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:458)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:739)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.os.Looper.loop(Looper.java:145)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5944)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at java.lang.reflect.Method.invoke(Native Method)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:372)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1389)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ Caused by: java.lang.IllegalArgumentException: Binary XML file line #12: Duplicate id 0x7f0e0099, tag null, or parent id 0x7f0e0098 with another fragment for com.google.android.gms.maps.MapFragment
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2135)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.app.Activity.onCreateView(Activity.java:5610)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.support.v7.app.AppCompatDelegateImplV11.callActivityOnCreateView(AppCompatDelegateImplV11.java:41)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(AppCompatDelegateImplV7.java:826)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:181)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:732)
07-19 16:04:25.720  12380-12380/fr.yougraph.homelesspasseul W/System.err﹕ ... 18 more
07-19 16:04:25.740  12380-12380/fr.yougraph.homelesspasseul D/AndroidRuntime﹕ Shutting down VM
07-19 16:04:25.740  12380-12380/fr.yougraph.homelesspasseul E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: fr.yougraph.homelesspasseul, PID: 12380
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
            at fr.yougraph.homelesspasseul.fragment.MapsFragment.onCreateView(MapsFragment.java:123)
            at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
            at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:458)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5944)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1389)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1184)

第一个例外,由于重复的mapfragment,导致mView为null,而我无法执行findViewById。

我看不到我在哪里错,我以前使用过寻呼机条,并且片段之间的切换效果很好,因此就像地图一样。

谢谢你的帮助

顺便说一下,我尝试了这些问题中给出的解决方案:

没有工作

我认为重复项来自:在MainActivity的onCreated中,您调用setupDrawerContent,它调用selectDrawerItem,默认情况下会设置片段= mMapfragment,但以前在Oncreate中,您已经在此行中创建了另一个MapsFragment:

  • mFragmentManager.beginTransaction()。replace(R.id.flContent,new MapsFragment())。commit();

所以我的建议是尝试将初始化更改为您已经声明的mMapFragment:

  • mFragmentManager.beginTransaction()。replace(R.id.flContent,mMapFragment).commit();
  相关解决方案