ViewPager错误:指定的子项已有父项。在viewpager适配器中调用片段时?

时间:2015-01-17 10:42:59

标签: java android android-viewpager mupdf

我已经实施了很多方法来解决这个问题,但它却一次又一次地出现。

我有一个Fragment EbookFragment,我在其中添加了ViewPager并在ViewPager我正在调用MUPDFActivity类,我转换为fragment

我从MUPDFActivity转换为Fragment后检查了Activity并且工作正常。我还使用测试ViewPager检查了Fragment并且它也正常工作但当我尝试在MUPDFACtivity中添加ViewPager时,它现在是fragment它会抛出以上例外。

以下是我的代码,请检查

在ViewPager中设置适配器:

 adapter = new EbookPagerAdapter(getActivity().getSupportFragmentManager(), lst);
            mPager.setAdapter(adapter);
            mPager.setOffscreenPageLimit(3);

MuPDFActivity.java:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        // return super.onCreateView(inflater, container, savedInstanceState);

        View rootView = inflater.inflate(R.layout.mupdf_fragment, container, false);
        timer.schedule(timerTask, 10000);
        pdfBean = (PDFBean) getArguments().getSerializable(LoginActivity.Extra_Value);

        LocationResult locationResult = new LocationResult() {
            @Override
            public void gotLocation(Location location) {
                // Got the location!
                if (location != null) {
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                }
            }
        };
        MyLocation myLocation = new MyLocation();
        myLocation.getLocation(getActivity(), locationResult);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        System.out.println(dateFormat.format(cal.getTime()));

        starttime = dateFormat.format(cal.getTime());
        startTimer = System.currentTimeMillis();

        mAlertBuilder = new AlertDialog.Builder(getActivity());

        if (core == null) {
            core = (MuPDFCore) getActivity().getLastNonConfigurationInstance();

            if (savedInstanceState != null && savedInstanceState.containsKey("FileName")) {
                mFileName = savedInstanceState.getString("FileName");
            }
        }
        if (core == null) {
            // Intent intent = getActivity().getIntent();
            byte buffer[] = null;
            // if (Intent.ACTION_VIEW.equals(intent.getAction())) {
            // Uri uri = intent.getData();
            Uri uri = Uri.parse(getArguments().getString(DisplayDataActivity.EXTRA_URL));
            System.out.println("URI to open is: " + uri);
            if (uri.toString().startsWith("content://")) {
                String reason = null;
                try {
                    InputStream is = getActivity().getContentResolver().openInputStream(uri);
                    int len = is.available();
                    buffer = new byte[len];
                    is.read(buffer, 0, len);
                    is.close();
                } catch (java.lang.OutOfMemoryError e) {
                    System.out.println("Out of memory during buffer reading");
                    reason = e.toString();
                } catch (Exception e) {
                    System.out.println("Exception reading from stream: " + e);

                    // Handle view requests from the Transformer Prime's
                    // file manager
                    // Hopefully other file managers will use this same
                    // scheme, if not
                    // using explicit paths.
                    // I'm hoping that this case below is no longer
                    // needed...but it's
                    // hard to test as the file manager seems to have
                    // changed in 4.x.
                    try {
                        Cursor cursor = getActivity().getContentResolver().query(uri, new String[] { "_data" }, null, null, null);
                        if (cursor.moveToFirst()) {
                            String str = cursor.getString(0);
                            if (str == null) {
                                reason = "Couldn't parse data in intent";
                            } else {
                                uri = Uri.parse(str);
                            }
                        }
                    } catch (Exception e2) {
                        System.out.println("Exception in Transformer Prime file manager code: " + e2);
                        reason = e2.toString();
                    }
                }
                if (reason != null) {
                    buffer = null;
                    Resources res = getResources();
                    // AlertDialog alert = mAlertBuilder.create();
                    // setTitle(String.format(res.getString(R.string.cannot_open_document_Reason),
                    // reason));
                    // alert.setButton(AlertDialog.BUTTON_POSITIVE,
                    // getString(R.string.dismiss), new
                    // DialogInterface.OnClickListener() {
                    // public void onClick(DialogInterface dialog, int which) {
                    // finish();
                    // }
                    // });
                    // alert.show();
                    return container;
                }
            }
            if (buffer != null) {
                // core = openBuffer(buffer, intent.getType());
            } else {
                core = openFile(Uri.decode(uri.getEncodedPath()));
            }
            SearchTaskResult.set(null);
        }
        if (core != null && core.needsPassword()) {
            requestPassword(savedInstanceState);
            return container;
        }
        if (core != null && core.countPages() == 0) {
            core = null;
        }
        // }
        if (core == null) {
            AlertDialog alert = mAlertBuilder.create();
            alert.setTitle(R.string.cannot_open_document);
            alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.dismiss), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // finish();
                }
            });
            alert.setOnCancelListener(new OnCancelListener() {

                @Override
                public void onCancel(DialogInterface dialog) {
                    // finish();
                }
            });
            alert.show();
            return container;
        }
        // createUI(savedInstanceState);

        if (core == null) {
            return rootView;
        }

        // Now create the UI.
        // First create the document view
        mDocView = new MuPDFReaderView(getActivity()) {
            @Override
            protected void onMoveToChild(int i) {
                if (core == null)
                    return;
                mPageNumberView.setText(String.format("%d / %d", i + 1, core.countPages()));
                mPageSlider.setMax((core.countPages() - 1) * mPageSliderRes);
                mPageSlider.setProgress(i * mPageSliderRes);
                pageNumber = i + 1;
                super.onMoveToChild(i);
            }

            @Override
            protected void onTapMainDocArea() {
                if (!mButtonsVisible) {
                    showButtons();
                } else {
                    if (mTopBarMode == TopBarMode.Main)
                        hideButtons();
                }
            }

            @Override
            protected void onDocMotion() {
                hideButtons();
            }

            @Override
            protected void onHit(Hit item) {
                switch (mTopBarMode) {
                case Annot:
                    if (item == Hit.Annotation) {
                        showButtons();
                        mTopBarMode = TopBarMode.Delete;
                        mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
                    }
                    break;
                case Delete:
                    mTopBarMode = TopBarMode.Annot;
                    mTopBarSwitcher.setDisplayedChild(mTopBarMode.ordinal());
                    // fall through
                default:
                    MuPDFView pageView = (MuPDFView) mDocView.getDisplayedView();
                    if (pageView != null)
                        pageView.deselectAnnotation();
                    break;
                }
            }
        };
        mDocView.setAdapter(new MuPDFPageAdapter(getActivity(), this, core));
        makeButtonsView();

        // Set up the page slider
        int smax = Math.max(core.countPages() - 1, 1);
        mPageSliderRes = ((10 + smax - 1) / smax) * 2;

        // Set the file-name text
        mFilenameView.setText(mFileName);

        // Activate the seekbar
        mPageSlider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            public void onStopTrackingTouch(SeekBar seekBar) {
                mDocView.setDisplayedViewIndex((seekBar.getProgress() + mPageSliderRes / 2) / mPageSliderRes);
            }

            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                updatePageNumView((progress + mPageSliderRes / 2) / mPageSliderRes);
            }
        });

        mLinkButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                setLinkHighlight(!mLinkHighlight);
            }
        });

        if (core.hasOutline()) {
            mOutlineButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    OutlineItem outline[] = core.getOutline();
                    if (outline != null) {
                        OutlineActivityData.get().items = outline;
                        Intent intent = new Intent(getActivity(), OutlineActivity.class);
                        startActivityForResult(intent, OUTLINE_REQUEST);
                    }
                }
            });
        } else {
            mOutlineButton.setVisibility(View.GONE);
        }

        // Reenstate last state if it was recorded
        SharedPreferences prefs = getActivity().getPreferences(Context.MODE_PRIVATE);
        mDocView.setDisplayedViewIndex(prefs.getInt("page" + mFileName, 0));

        if (savedInstanceState == null || !savedInstanceState.getBoolean("ButtonsHidden", false))
            showButtons();

        if (savedInstanceState != null && savedInstanceState.getBoolean("SearchMode", false))
            searchModeOn();
        RelativeLayout rv = (RelativeLayout) rootView.findViewById(R.id.rv);
        rv.addView(mDocView);
//      rv.addView(mButtonsView);
        setLinkHighlight(true);
        // LinearLayout.LayoutParams relativeParams =
        // (LinearLayout.LayoutParams) layout.getLayoutParams();
        // relativeParams.setMargins(0, 96, 0, 0);
        // layout.setLayoutParams(relativeParams);

        return rootView;

    }

EBookPagerAdapter:

 public class EbookPagerAdapter extends FragmentStatePagerAdapter implements Serializable {
        ArrayList<EbookBean>  list;
        FragmentManager fm;
        public EbookPagerAdapter(FragmentManager fm, ArrayList<EbookBean>  pdfList) {
            super(fm);
            this.fm = fm;
        list = pdfList;
    }

    @Override
    public float getPageWidth(int position) {

        return 1.0f;
    }

    @Override
    public Fragment getItem(int i) {
        EbookBean pdf = list.get(i);
//      Fragment fragment = new SampleTest();
        Fragment fragment = new MuPDFFragment();
        Bundle args = new Bundle();
        args.putString(DisplayDataActivity.EXTRA_URL, LoginActivity.path + pdf.getPdf_name());
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list.size();
    }
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) 
    {
            FragmentTransaction ft= fm.beginTransaction();
            ft.remove((Fragment) object);
            ft.commit();
    }
}

错误:

01-17 09:57:59.077: E/AndroidRuntime(8220): FATAL EXCEPTION: main
01-17 09:57:59.077: E/AndroidRuntime(8220): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.ViewGroup.addViewInner(ViewGroup.java:3509)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.ViewGroup.addView(ViewGroup.java:3380)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.ViewGroup.addView(ViewGroup.java:3325)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.ViewGroup.addView(ViewGroup.java:3301)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.support.v4.app.NoSaveStateFrameLayout.wrap(NoSaveStateFrameLayout.java:40)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:946)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1121)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1484)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:482)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.View.measure(View.java:15848)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.widget.LinearLayout.measureHorizontal(LinearLayout.java:1052)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:590)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.View.measure(View.java:15848)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.View.measure(View.java:15848)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.View.measure(View.java:15848)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.support.v4.widget.DrawerLayout.onMeasure(DrawerLayout.java:762)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.View.measure(View.java:15848)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.View.measure(View.java:15848)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.View.measure(View.java:15848)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2189)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.View.measure(View.java:15848)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1905)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1104)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1284)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.Choreographer.doCallbacks(Choreographer.java:562)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.Choreographer.doFrame(Choreographer.java:532)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.os.Handler.handleCallback(Handler.java:730)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.os.Looper.loop(Looper.java:137)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at android.app.ActivityThread.main(ActivityThread.java:5103)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at java.lang.reflect.Method.invokeNative(Native Method)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at java.lang.reflect.Method.invoke(Method.java:525)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-17 09:57:59.077: E/AndroidRuntime(8220):     at dalvik.system.NativeStart.main(Native Method)

0 个答案:

没有答案