Search code examples
androidandroid-tabslayout-inflaterandroid-tablayout

Error while setting custom view for each tab in Tab layout


I am getting error while setting up custom views for tabs in tab layout. Every tab runs fine on the first run, but when I swipe between tabs, runtime error appears. I am just trying out tab layout for the first time, can somebody help me with this ?

E/AndroidRuntime: FATAL EXCEPTION: main Process: com.rocks.mafia.entrancesecurity, PID: 18095
              android.view.InflateException: Binary XML file line #6: Binary XML file line #6: Error inflating class fragment
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
                  at com.rocks.mafia.entrancesecurity.MainActivity$PlaceholderFragment.onCreateView(MainActivity.java:137)
                  at android.support.v4.app.Fragment.performCreateView(Fragment.java:2080)
                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
                  at android.support.v4.app.FragmentManagerImpl.attachFragment(FragmentManager.java:1468)
                  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:791)
                  at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1638)
                  at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:679)
                  at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143)
                  at android.support.v4.view.ViewPager.populate(ViewPager.java:1240)
                  at android.support.v4.view.ViewPager.populate(ViewPager.java:1088)
                  at android.support.v4.view.ViewPager$3.run(ViewPager.java:275)
                  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:894)
                  at android.view.Choreographer.doCallbacks(Choreographer.java:696)
                  at android.view.Choreographer.doFrame(Choreographer.java:628)
                  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:880)
                  at android.os.Handler.handleCallback(Handler.java:815)
                  at android.os.Handler.dispatchMessage(Handler.java:104)
                  at android.os.Looper.loop(Looper.java:207)
                  at android.app.ActivityThread.main(ActivityThread.java:5740)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:766)
               Caused by: android.view.InflateException: Binary XML file line #6: Error inflating class fragment
                  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782)
                  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
                  at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
                  at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:423) 
                  at com.rocks.mafia.entrancesecurity.MainActivity$PlaceholderFragment.onCreateView(MainActivity.java:137) 
                  at android.support.v4.app.Fragment.performCreateView(Fragment.java:2080) 
                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108) 
                  at android.support.v4.app.FragmentManagerImpl.attachFragment(FragmentManager.java:1468) 
                  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:791) 
                  at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1638) 
                  at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:679) 
                  at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143) 
                  at android.support.v4.view.ViewPager.populate(ViewPager.java:1240) 
                  at android.support.v4.view.ViewPager.populate(ViewPager.java:1088) 
                  at android.support.v4.view.ViewPager$3.run(ViewPager.java:275) 
                  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:894) 
                  at android.view.Choreographer.doCallbacks(Choreographer.java:696) 
                  at android.view.Choreographer.doFrame(Choreographer.java:628) 
                  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:880) 
                  at android.os.Handler.handleCallback(Handler.java:815) 
                  at android.os.Handler.dispatchMessage(Handler.java:104) 
                  at android.os.Looper.loop(Looper.java:207) 
                  at android.app.ActivityThread.main(ActivityThread.java:5740) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:766) 
               Caused by: java.lang.IllegalArgumentException: Binary XML file line #6: Duplicate id 0x7f0c009f, tag null, or parent id 0xffffffff with another fragment for com.rocks.mafia.entrancesecurity.HistoryFragment
                  at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2422)
                  at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
                  at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:186)
                  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:746)
                  at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704) 
                  at android.view.LayoutInflater.rInflate(LayoutInflater.java:835) 
                  at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798) 
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:515) 
                  at android.view.LayoutInflater.inflate(LayoutInflater.java:423) 
                  at com.rocks.mafia.entrancesecurity.MainActivity$PlaceholderFragment.onCreateView(MainActivity.java:137) 
                  at android.support.v4.app.Fragment.performCreateView(Fragment.java:2080) 
                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108) 
                  at android.support.v4.app.FragmentManagerImpl.attachFragment(FragmentManager.java:1468) 
                  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:791) 
                  at android.support.v4.app.FragmentManagerImpl.execSingleAction(FragmentManager.java:1638) 
                  at android.support.v4.app.BackStackRecord.commitNowAllowingStateLoss(BackStackRecord.java:679) 
                  at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:143) 
                  at android.support.v4.view.ViewPager.populate(ViewPager.java:1240) 
                  at android.support.v4.view.ViewPager.populate(ViewPager.java:1088) 
                  at android.support.v4.view.ViewPager$3.run(ViewPager.java:275) 
                  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:894) 
                  at android.view.Choreographer.doCallbacks(Choreographer.java:696) 
                  at android.view.Choreographer.doFrame(Choreographer.java:628) 
                  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:880) 
                  at android.os.Handler.handleCallback(Handler.java:815) 
                  at android.os.Handler.dispatchMessage(Handler.java:104) 
                  at android.os.Looper.loop(Looper.java:207) 
                  at android.app.ActivityThread.main(ActivityThread.java:5740) 
                  at java.lang.reflect.Method.invoke(Native Method) 
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905) 
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:766) 

MainActivity.java

package com.rocks.mafia.entrancesecurity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);
        mViewPager.setCurrentItem(1);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(mViewPager);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

    }


    @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_main, menu);
        return true;
    }

    @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();

        //noinspection SimplifiableIfStatement

        switch (id) {
            case R.id.action_logout:
                SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
                SharedPreferences.Editor editor = sharedPref.edit();
                editor.putBoolean(getString(R.string.isLogin), false);
                editor.commit();
                Intent intent = new Intent(this, WelcomeActivity.class);
                startActivity(intent);
                break;
            case R.id.action_settings:
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {
        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
                View rootView = inflater.inflate(R.layout.fragment_profile, container, false);
                return rootView;
            } else if (getArguments().getInt(ARG_SECTION_NUMBER) == 3) {
                View rootView = inflater.inflate(R.layout.history_display, container, false);
                return rootView;
            }
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
            return rootView;
        }
    }

    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 3;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Profile";
                case 1:
                    return "Requests";
                case 2:
                    return "History";
            }
            return null;
        }
    }
}
`

history_display.xml

  <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent">

        <fragment
            android:id="@+id/historyFrag"
            android:name="com.rocks.mafia.entrancesecurity.HistoryFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </fragment>

    </LinearLayout>

fragment_profile.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.rocks.mafia.entrancesecurity.ProfileFragment">

    <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/app_bar"
            android:layout_width="match_parent"
            android:layout_height="218dp"
            android:background="@color/colorPrimary"
            android:theme="@style/AppTheme.AppBarOverlay">

            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/toolbar_layout"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                app:contentScrim="?attr/colorPrimary"
                app:expandedTitleMarginEnd="64dp"
                app:expandedTitleMarginStart="48dp"
                app:layout_scrollFlags="scroll|exitUntilCollapsed">

                <ImageView
                    android:layout_width="match_parent"
                    android:layout_height="150dp"
                    android:adjustViewBounds="true"
                    android:src="@drawable/ln_logo"
                    app:layout_collapseMode="parallax"
                    app:layout_collapseParallaxMultiplier="0.7" />

                <android.support.v7.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?android:attr/actionBarSize"
                    android:minHeight="?android:attr/actionBarSize"
                    app:layout_collapseMode="pin"
                    app:layout_scrollFlags="scroll|exitUntilCollapsed"
                    app:popupTheme="@style/AppTheme.PopupOverlay" />

            </android.support.design.widget.CollapsingToolbarLayout>
        </android.support.design.widget.AppBarLayout>

        <include layout="@layout/content_profile" />

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/fab_margin"
            android:src="@drawable/ic_star_black"
            app:layout_anchor="@id/app_bar"
            app:layout_anchorGravity="bottom|end" />

    </android.support.design.widget.CoordinatorLayout>

</FrameLayout>

fragment_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.rocks.mafia.entrancesecurity.MainActivity$PlaceholderFragment">

    <TextView
        android:id="@+id/section_label"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

Solution

  • The answer is simple : don't use xml fragments at all. It is bad supported, has a lot of limitations, like that with which you met.
    The problem is that two same xml fragments ( without workarounds) couldn't exist together, because them share same fragment id. The crash happends when history fragment tried to recreate it's view, due to page changing process, but previous one still hadn't been garbage collected.

    Sure, you still could setOffscreenPageLimit on ViewPager to 2 in your case ( all views will stay in memory) , but you should just remove you xml fragment and attach it programmatically if really needed.