0

У меня три вкладки, я могу вернуться со второй кладки на первую, но когда я возвращаюсь с третьей на вторую, то уже не могу вернуться на первую и программа отваливается в логах пишет.

В первой вкладке два фрагмента

<fragment

    android:name="com.example.eldos.callreport.Fragment1"
    android:id="@+id/frag1"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    tools:layout="@layout/fragment1"/>

<fragment
    android:name="com.example.eldos.callreport.Fragment2"
    android:id="@+id/frag2"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    tools:layout="@layout/fragment2"/>

код где создаются вкладки

public class ScreenOne extends Fragment {

    private SlidingTabLayout mSlidingTabLayout;

    private ViewPager mViewPager;

    public ScreenOne() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.screen_first, container, false);
        Log.i("log", "onCreateView");

        return rootView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        // Get the ViewPager and set it's PagerAdapter so that it can display items
        mViewPager = (ViewPager) view.findViewById(R.id.viewpager);
        mViewPager.setAdapter(new SamplePagerAdapter());


        // Give the SlidingTabLayout the ViewPager, this must be
        // done AFTER the ViewPager has had it's PagerAdapter set.
        mSlidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.sliding_tabs);
        mSlidingTabLayout.setViewPager(mViewPager);


    }

    // Adapter
    class SamplePagerAdapter extends PagerAdapter {

        /**
         * Return the number of pages to display
         */
        @Override
        public int getCount() {
            return 4;
        }

        /**
         * Return true if the value returned from is the same object as the View
         * added to the ViewPager.
         */
        @Override
        public boolean isViewFromObject(View view, Object o) {
            return o == view;
        }

        /**
         * Return the title of the item at position. This is important as what
         * this method returns is what is displayed in the SlidingTabLayout.
         */
        @Override
        public CharSequence getPageTitle(int position) {
            return "Screen " + (position + 1);
        }

        /**
         * Instantiate the View which should be displayed at position. Here we
         * inflate a layout from the apps resources and then change the text
         * view to signify the position.
         */
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // Inflate a new layout from our resources
            View view = null;
            if(position == 0){
                 view = getActivity().getLayoutInflater().inflate(R.layout.activity_main,container, false);
                container.addView(view);
//                TextView title = (TextView) view.findViewById(R.id.item_title);
//                title.setText("It's first page");
            }
            // Add the newly created View to the ViewPager


            // Retrieve a TextView from the inflated View, and update it's text
            if(position == 1) {
                 view = getActivity().getLayoutInflater().inflate(R.layout.pager_item, container, false);
                container.addView(view);
                TextView title = (TextView) view.findViewById(R.id.item_title);
                title.setText("It's first page");
            }
            if(position == 2) {
                 view = getActivity().getLayoutInflater().inflate(R.layout.pager_item, container, false);
                container.addView(view);
                TextView title = (TextView) view.findViewById(R.id.item_title);
                title.setText("It's first page");
            }
            else {
                view = getActivity().getLayoutInflater().inflate(R.layout.pager_item, container, false);
                container.addView(view);
                TextView title = (TextView) view.findViewById(R.id.item_title);
                title.setText("It's first page");
            }
            // Return the View
            return view;
        }

        /**
         * Destroy the item from the ViewPager. In our case this is simply
         * removing the View.
         */
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }
}

Выводит ошибку, когда я перелистываю с третьей на вторую, и даже если я просто задеваю эту вторую вкладку,

12-22 08:50:42.060
1558-1558/com.example.eldos.callreport E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.example.eldos.callreport, PID: 1558 android.view.InflateException: Binary XML file line #18: Error inflating class fragment at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713) at android.view.LayoutInflater.rInflate(LayoutInflater.java:755) at android.view.LayoutInflater.inflate(LayoutInflater.java:492) at android.view.LayoutInflater.inflate(LayoutInflater.java:397) at com.example.eldos.callreport.fragments.ScreenOne$SamplePagerAdapter.instantiateItem(ScreenOne.java:92) at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:837) at android.support.v4.view.ViewPager.populate(ViewPager.java:1021) 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:761) at android.view.Choreographer.doCallbacks(Choreographer.java:574) at android.view.Choreographer.doFrame(Choreographer.java:543) at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5001) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.IllegalArgumentException: Binary XML file line #18: Duplicate id 0x7f090040, tag null, or parent id 0x0 with another fragment for com.example.eldos.callreport.Fragment1 at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2164) at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:297) at android.support.v7.app.ActionBarActivity.onCreateView(ActionBarActivity.java:547) at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:685)             at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)             at android.view.LayoutInflater.inflate(LayoutInflater.java:492)             at android.view.LayoutInflater.inflate(LayoutInflater.java:397)             at com.example.eldos.callreport.fragments.ScreenOne$SamplePagerAdapter.instantiateItem(ScreenOne.java:92)             at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:837)             at android.support.v4.view.ViewPager.populate(ViewPager.java:1021)             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:761)             at android.view.Choreographer.doCallbacks(Choreographer.java:574)             at android.view.Choreographer.doFrame(Choreographer.java:543)             at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)             at android.os.Handler.handleCallback(Handler.java:733)             at android.os.Handler.dispatchMessage(Handler.java:95)             at android.os.Looper.loop(Looper.java:136)             at android.app.ActivityThread.main(ActivityThread.java:5001)             at java.lang.reflect.Method.invokeNative(Native Method)             at java.lang.reflect.Method.invoke(Method.java:515)             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)             at dalvik.system.NativeStart.main(Native Method)

1
  • Вот такая ошибка: >aused by: java.lang.IllegalArgumentException: Binary XML file line #18: Duplicate id 0x7f090040, tag null, or parent id 0x0 with another fragment for com.example.eldos.callreport.Fragment1 at
    – J Mas
    23 дек 2014 в 5:56

1 ответ 1

2

У Вас в методе instantiateItem выполняются 2 условия, кроме случая, когда position = 2. Например, если position = 0, выполняется условие if(position == 0) и else из if(position == 2). Используйте switch / case

@Override
public Object instantiateItem(ViewGroup container, int position) {

    View view = getActivity().getLayoutInflater().inflate(R.layout.pager_item,container, false);
    container.addView(view);
    TextView title = (TextView) view.findViewById(R.id.item_title)

    switch(position){
        case 0:
            title.setText("One");
        case 1:
            title.setText("Two");
        case 2:
            title.setText("Two+One");
        case 3:
            title.setText("Lastone");
    }

    return view;
}

Надеюсь, это то, о чем вы спрашиваете.

7
  • да, уже исправил, но дело не в этом, дело в том, что этот фрагмент уничтожается и потом заново создается, а заново он почему не может сформироваться, хотя там только одна кнопка и то не рабочая, или как-то можно по-другому подставлять ему страницы, кроме фрагментов.
    – J Mas
    22 дек 2014 в 14:30
  • фрагмент ScreenOne уничтожается? 22 дек 2014 в 15:14
  • Я просто смотрю код, который вы используете из github, там вроде все должно работать. Не пойму, зачем вы пытаетесь засунуть в контейнер одно и тоже. 22 дек 2014 в 15:17
  • вот здесь public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } он уничтожается, но даже если я убираю эту строку, она все равно заново пытается создавать, вот надо бы как-то сделать, чтобы она заново не создавала, то есть могла как-то проверять есть ли такой или нету, или нормально пересоздавать, что более предпочтительно,
    – J Mas
    22 дек 2014 в 16:06
  • у меня вопрос, как я могу создавать вьюшки, не используя фрагменты, я создаю вью, направляя его на xml код, где прописан фрагмент, может, можно еще как-то по-другому более предпочтительно. В контейнер я сую одно и то же, это только тест, позже я переделаю, когда я до конца решу эту проблему.
    – J Mas
    22 дек 2014 в 16:07

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.