【问题标题】:android oncreateview throwing inflateException using viewpagerandroid oncreateview 使用 viewpager 抛出 inflateException
【发布时间】:2015-05-02 14:16:51
【问题描述】:

我正在尝试将谷歌地图片段放入另一个片段中,而该片段是 viewpager 的一部分。它的初始部分有效,地图片段被放在我的手机屏幕上。

该活动使用一个具有 3 个片段的 viewpager,其中包含地图片段的片段是您看到的第一个片段,但是当我滑动到最后一个片段然后返回中间片段时,应用程序崩溃并且我在我的第一个片段(带有地图的片段)的 OnCreateView 方法中得到一个 inflateException。

我不知道如何解决这个问题,而且我没有尝试过让它工作。对此的任何帮助将不胜感激。

其中包含 mapfragment 的片段。

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/tV_welkomtekst"
    android:textSize="25dp"
    android:layout_gravity="center"/>

<TextView
    android:text="@string/sportdropdown_tekst"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="25dp"/>

<Spinner
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/spinSporten"></Spinner>

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

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/tekst_startWorkout"/>

保存片段的活动。

package desomer_michael_2app.desomer_michael_eindopdracht_app;

import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;


public class SportActivity extends FragmentActivity implements SportStatsFragment.OnSportStatsFragmentInteractionListener, SportStartFragment.OnSportStartFragmentInteractionListener, SportBadgesFragment.OnSportBadgesFragmentInteractionListener{

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

    ViewPager viewPager = (ViewPager) findViewById(R.id.pager);

    viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));


    /*
    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction()
                .add(R.id.container, new SportStartFragment())
                .commit();
    }
    */
}

protected void onSaveInstanceState(Bundle outState){
    super.onSaveInstanceState(outState);
    //getSupportFragmentManager().putFragment(outState, "sportStartFragment", );
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_sport, menu);

    return true;
}

public void uitloggen(){
    //Intent i = new Intent("android.intent.action.MAIN");
    //startActivity(i);
    finish();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    switch(id){
        case R.id.log_out:
            uitloggen();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }



}


}

浏览器

package desomer_michael_2app.desomer_michael_eindopdracht_app;

import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;

/**
 * Created by Michaël Desomer on 25/04/2015.
 */
public class ViewPagerAdapter extends FragmentPagerAdapter{
final int PAGE_COUNT = 3;

private String tabtitles[] = new String[]{"Start","Stats","Badges"};

Context context;

public ViewPagerAdapter(FragmentManager fm){
    super(fm);
}

@Override
public Fragment getItem(int i) {
    switch(i){
        case 0:
            SportStartFragment sportStartFragment = new SportStartFragment();

            return sportStartFragment;

        case 1:
            SportStatsFragment sportStatsFragment = new SportStatsFragment();
            return sportStatsFragment;

        case 2:
            SportBadgesFragment sportBadgesFragment = new SportBadgesFragment();
            return sportBadgesFragment;

        default:
            return null;
    }
    //return null;
}

@Override
public CharSequence getPageTitle(int position){
    return tabtitles[position];
}

@Override
public int getCount() {
    return PAGE_COUNT;
}
}

我的安卓清单

<uses-permission android:name="android.permission.INTERNET" />
<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="android.permission.ACCESS_NETWORK_STATE" />

<meta-data
    android:name="com.google.android.gms.version"
    android:value="@integer/google_play_services_version" />

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".LoginRegistreerActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".SportActivity"
        android:label="@string/title_activity_sport" >
        <intent-filter>
            <action android:name="create_sportactivity" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value=""/>
</application>

错误信息

05-02 15:57:01.360  19662-19662/desomer_michael_2app.desomer_michael_eindopdracht_app E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.view.InflateException: Binary XML file line #30: Error inflating class fragment
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:719)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:498)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:398)
        at desomer_michael_2app.desomer_michael_eindopdracht_app.SportStartFragment.onCreateView(SportStartFragment.java:57)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
        at android.support.v4.app.FragmentManagerImpl.attachFragment(FragmentManager.java:1302)
        at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:729)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
        at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:486)
        at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
        at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
        at android.support.v4.view.ViewPager$3.run(ViewPager.java:249)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791)
        at android.view.Choreographer.doCallbacks(Choreographer.java:591)
        at android.view.Choreographer.doFrame(Choreographer.java:560)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:777)
        at android.os.Handler.handleCallback(Handler.java:730)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:176)
        at android.app.ActivityThread.main(ActivityThread.java:5419)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:525)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.IllegalArgumentException: Binary XML file line #30: Duplicate id 0x7f09006d, tag null, or parent id 0xffffffff with another fragment for com.google.android.gms.maps.MapFragment
       at desomer_michael_2app.desomer_michael_eindopdracht_app.SportStartFragment.onCreateView(SportStartFragment.java:57)
(there were quite bit more, but i couldn't get them all in the code format)

SportStatsFragment

package desomer_michael_2app.desomer_michael_eindopdracht_app;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link SportStatsFragment.OnSportStatsFragmentInteractionListener} interface
 * to handle interaction events.
 */
public class SportStatsFragment extends Fragment {

    private OnSportStatsFragmentInteractionListener mListener;

    public SportStatsFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_sport_stats, container, false);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnSportStatsFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnSportStatsFragmentInteractionListener {
        // TODO: Update argument type and name

    }

}
 

           

【问题讨论】:

    标签: android google-maps android-fragments android-viewpager


    【解决方案1】:

    问题是您一次又一次地使用同一张地图(重复 id 0x7f09006d)而没有破坏。

    案例是销毁片段

    @Override
    public void onDestroyView()
    {
       super.onDestroyView();
       Fragment fragment = (getFragmentManager().findFragmentById(R.id.map));  
       FragmentTransaction ft= getActivity().getSupportFragmentManager().beginTransaction();
       ft.remove(fragment);
       ft.commit();
    }
    

    【讨论】:

    • 我现在得到一个空指针异常。当我调试时,它显示该片段为空。不过我很欣赏这个答案:)
    • FragmentPagerAdapter 必须将您的片段保存在内存中,但是使用地图会有些麻烦。发布您的SportStatsFragment 并尝试FragmentStatePagerAdapter
    • 刚刚添加到帖子中
    【解决方案2】:
    package com.panorma.views.fragments.contact;
    
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentManager;
    import android.util.Log;
    import android.view.InflateException;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    
    import com.google.android.gms.maps.CameraUpdate;
    import com.google.android.gms.maps.CameraUpdateFactory;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.MapsInitializer;
    import com.google.android.gms.maps.SupportMapFragment;
    import com.google.android.gms.maps.model.LatLndg;
    import com.google.android.gms.maps.model.MarkerOptions;
    import com.panorma.R;
    
    /**
     * Created by aateek on 3/10/2016.
     */
    // In this case, the fragment displays simple text based on the page
    public class MapViewPagerFragment extends Fragment {
    
        private static View rootView;
        private final double LATITUDE = *********;
        private final double LONGITUDE = ********;
    
        GoogleMap googleMap;
        private SupportMapFragment mapFrag;
    
        @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_contacts, container, false);
            } catch (InflateException e) {
            /* map is already there, just return view as it is */
                Log.d("InflateException", "onCreateView: ");
            }
            initMap();
    
            return rootView;
        }
    
    
        private void initMap() {
    
            LatLng location = new LatLng(LATITUDE, LONGITUDE);
            FragmentManager fm = getChildFragmentManager();
            mapFrag = (SupportMapFragment) fm.findFragmentById(
                    R.id.map);
            if (mapFrag != null) {
                googleMap = mapFrag.getMap();
            }
    
            if (googleMap != null) {
                googleMap.getUiSettings().setMyLocationButtonEnabled(false);
                googleMap.addMarker(new MarkerOptions().position(location));
                MapsInitializer.initialize(this.getActivity());
                // Updates the location and zoom of the MapView
                CameraUpdate initalUpdate = CameraUpdateFactory.newLatLngZoom(
                        location, 17.0f);
    
                googleMap.animateCamera(initalUpdate);
            }
    
        }
    }
    

    【讨论】:

    • 你应该用英文添加你的代码描述。这有助于理解它的作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-16
    • 2022-10-18
    • 2012-02-12
    • 2015-08-12
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多