0

При использовании вкладок выходит ошибка. У меня три вкладки, первые две создаются нормально, но третья добавляться не хочет, даже если меняю местами вкладки, третья не создается. Когда дело доходит до создания третьей вкладки, выходит ошибка.

12-29 04:31:02.857    3066-3066/com.example.eldos.callreport E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.eldos.callreport, PID: 3066
    android.view.InflateException: Binary XML file line #8: 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:119)
            at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:837)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:1053)
            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 #8: Duplicate id 0x7f09007b, tag null, or parent id 0xffffffff with another fragment for com.example.eldos.callreport.fragments.ScreenThree
            at android.app.Activity.onCreateView(Activity.java:4791)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:689)
            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:119)
            at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:837)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:1053)
            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)

package com.example.eldos.callreport.fragments;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.eldos.callreport.R;
import com.example.eldos.callreport.view.SlidingTabLayout;

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());
        mViewPager.setBackgroundColor(Color.parseColor("#FFFAFA"));
        // 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.setElevation(34);
//        mSlidingTabLayout.setcolo
        mSlidingTabLayout.setViewPager(mViewPager);

    }

    // Adapter
    class SamplePagerAdapter extends PagerAdapter {

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

        /**
         * 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) {
            String title = null;
            if(position == 1)
                title = "Звонки по абонентам";
            else if(position == 0)
                title = "Звонки по опреаторам";
            else
            title = "USSD";
            return title;
        }

        /**
         * 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.
         */
        View view = null;
        int i = 0;
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            // Inflate a new layout from our resources

                if (position == 0) {
                    view = getActivity().getLayoutInflater().inflate(R.layout.activity_main, container, false);
                    container.addView(view);

                    i++;
                    //                TextView title = (TextView) view.findViewById(R.id.item_title);
                    //                title.setText("It's first page");
                } else if (position == 1) {

                    try {
                        view = getActivity().getLayoutInflater().inflate(R.layout.two_tab, container, false);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    container.addView(view);
                    i++;
                } else if (position == 2) {
                    view = getActivity().getLayoutInflater().inflate(R.layout.three_tab, container, false);
                    container.addView(view);

//                    view = getActivity().getLayoutInflater().inflate(R.layout.pager_item, container, false);

//                    TextView title = (TextView) view.findViewById(R.id.item_title);
//                    title.setText("It's 3 page");
                        i++;
                }

            Log.i("Screen One", "created view " + position);
            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) {
//            if(position == 0)
                container.removeView((View) object);
//
            super.destroyItem(container,position,object);
            Log.i("Screen One", "destroy view " + position);
        }
    }
}

fragment.xml. Такой код:

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

    <fragment
        android:name="com.example.eldos.callreport.fragments.ScreenThree"
        android:id="@+id/frag3"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        tools:layout="@layout/fragmentfor3scr"/>

</LinearLayout>

Другие вкладки я создаю так же, но с другими фрагментами, а вот если вместо любого фрагмента добавить просто текст - все работает прекрасно.

То есть вкладки работают, если в этих трех вкладках работает два фрагмента и вместо третьего просто текст, а вот если три фрагмента, то так уже не работает и вываливает ошибку.

view = getActivity().getLayoutInflater().inflate(R.layout.pager_item, container, false);

TextView title = (TextView) view.findViewById(R.id.item_title);
title.setText("It's 3 page");}

Обновление

Проблема решилась, дело было в том, что были одинаковые id у двух табов в laoyut файлах.

Обновление

Может ли кто-нибудь подсказать, как мне создавать вкладки. Я нахожу лайот файл, а в этом файле указываю создание фрагмента с указанием класса, а этот фрагмент уже создает view, но я думаю, это неправильно. Как же все-таки создавать? Что-то типа:

Fragment1  fr = new Fragment1();
container.add(fr);

1 ответ 1

1

Ошибка-то говорит о том, что у вас 2 одинаковых ID.

1
  • как бы уже написал об этом сам
    – J Mas
    30 дек 2014 в 2:37

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

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