Viewpager:如果页面得到去掉下面几页的内容得到移除网页内容内容、移除、页面、网页

2023-09-08 00:26:11 作者:Dummer、浅时光

(如果有人需要更多的信息,或者更好的描述让我知道)

您好我包括从这里viewPagerLibrary: http://viewpagerindicator.com/#introduction 今天在我的项目。

Hello i included the viewPagerLibrary from here: http://viewpagerindicator.com/#introduction today in my project.

没有我得到一个非常奇怪的问题:如果我添加一个网站或网页(姑且称之为网站在接下来的几行),并再次将其删除一切正常。但是,如果我尝试添加不同的网页(这些网页是它实现了一个BaseFragment类不同Fragements)的第一页的内容所示。如果我增加了几页,并删除一个插图中那些页面同样的事情发生。这是被删除的页面后,页面现在显示了删除的页面内容。

No i get a really strange problem: If i add a site or page (let's call it site in the next few lines) and remove it again everything is ok. But if i try to add a different page (Those pages are different Fragements which implements a BaseFragment class) the content of the first page is shown. The same thing happens if i add a few pages and delete one inbetween those pages. The page which was after the deleted page shows now the deleted pages content.

这个bug的一个例子:现在的问题是。如果我说FragmentB之后添加碎裂,然后我删除碎裂,FragmentB得到碎裂的视图/内容。奇怪的是,对象是正确的(所以适配器返回正确的对象),标题也是正确的。

An example of this bug: The problem now is. If i add FragmentA after that FragmentB, then i delete FragmentA, FragmentB gets the view/content of FragmentA. The strange thing is, the object is the correct one (So the adapter return the correct object) and the Title is also the correct one.

在我的主要创建我的传呼机,指示器和适配器是这样的:

In my main i create my Pager, Indicator and Adapter this way:

    Cfg.mAdapter = new FragmentAdapter(getSupportFragmentManager());

    Cfg.mPager = (ViewPager)findViewById(R.id.pager);
    Cfg.mPager.setAdapter(Cfg.mAdapter);

    Cfg.mIndicator = (TabPageIndicator)findViewById(R.id.indicator);
    Cfg.mIndicator.setViewPager(Cfg.mPager);

    //We set this on the indicator, NOT the pager
    Cfg.mIndicator.setOnPageChangeListener(TabHelper.onPageChangeListener);

(所述CFG是一个静态文件来存储对于使用那些东西)

(The Cfg is a static file to store those things for the usage)

我BaseFragment如下所示:

My BaseFragment looks like the following:

public class BaseFragment extends Fragment{

    public static int FILE_FRAGMENT = 0;
    public static int FTP_FRAGMENT = 1;
    public static int ADDFTP_FRAGMENT = 2;
    public static int PREVIEW_FRAGMENT = 3;
    public static int CSS_FRAGMENT = 4;
    public static int BOOKS_FRAGMENT = 5;
    public static int SNIPPETS_FRAGMENT = 6;

    //private int id;
    private int typ;
    private String title;

    public int getTyp() {
        return typ;
    }

    public void setTyp(int typ) {
        this.typ = typ;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}

一个片段看起来像这样(我想其他碎片没有区别):

One of the Fragments looks like this (I think the other fragments make no difference):

public class FtpFragment extends BaseFragment {
    private static RowLayout rowLayout_view;

    public FtpFragment() {
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init_data();
    }

    public static void init_data()
    {
        //Remove child for update
        rowLayout_view.removeAllViews();

        List<FtpData> ftps = FtpStorage.getInstance().getFtps();

        if (ftps != null) {
            for (FtpData f : ftps) {
                View inflatedView;
                inflatedView = View.inflate(Cfg.ctx, R.layout.ftp, null);
                inflatedView.setOnClickListener(button_ftp_listener);
                inflatedView.setOnLongClickListener(button_ftp_longClickListener);
                inflatedView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, Converter.convertFromDPtoPixel(160.0f)));
                inflatedView.setTag(f);
                inflatedView.findViewById(R.id.book_imageview).setBackgroundDrawable(
                                Cfg.ctx.getResources().getDrawable(R.drawable.nopreview));


                ((TextView) inflatedView.findViewById(R.id.book_textview)).setText(f.nickname);

                rowLayout_view.addView(inflatedView);
            }
        }
    }

    @Override

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_ftp, container, false);
    rowLayout_view = (RowLayout) v.findViewById(R.id.rowLayout_ftps);
    return v;
}

@Override
public String getTitle() {
    return "FTPs";
}

@Override
public int getTyp() {
    return BaseFragment.FTP_FRAGMENT;
}

@Override
public void setTyp(int typ) {
    super.setTyp(typ);
}

}

要删除或添加页面我称之为:

To remove or add a page i call this:

public static void addNewTab(BaseFragment fragment)
{
    Cfg.mAdapter.addItem(fragment);
    Cfg.mPager.setCurrentItem(Cfg.mAdapter.getCount());
    Cfg.mIndicator.notifyDataSetChanged();
}

public static void deleteActTab()
{
    Cfg.mAdapter.removeItem(Cfg.mAdapter.getActPage());
    Cfg.mIndicator.notifyDataSetChanged();
}

这就是今天的适配器:

And that's the adapter:

public class FragmentAdapter extends FragmentPagerAdapter implements TitleProvider{
    public List<BaseFragment> fragments = new LinkedList<BaseFragment>();

    private int actPage;

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


    public void setActPage(int actPage) {
        Lg.d("setActPage: " + actPage + " : " + fragments.get(actPage).toString());
        this.actPage = actPage; 
    }

    public void addItem(BaseFragment fragment)
    {
        Lg.d("addItem: " + fragment.toString());
        fragments.add(fragment);
    }

    public void removeItem(int index)
    {
        if(index < getCount()){
            Lg.d("RemoveItem: " + index + " : " + fragments.get(index).toString());
            fragments.remove(index);
        }
    }

    public BaseFragment getActFragment()
    {
        return getItem(getActPage());
    }

    public int getActPage() {
        return actPage;
    }

    @Override
    public BaseFragment getItem(int position) {
        if(position < getCount())
        {
            Lg.v("getItem: " + fragments.get(position));
            return fragments.get(position);
        }
        else
            return null;
    }

    @Override
    public int getCount() {
        return fragments.size();
    }

    @Override
    public String getTitle(int position) {
        Lg.v("Get Title: " + fragments.get(position).getTitle());
        return fragments.get(position).getTitle();
    }

}

是的,我希望有人能帮助我。

Yeah i hope someone can help me.

如果我忘带了什么东西让我konw。

If i forgot something let me konw.

在此先感谢,迈克

Thanks in advance, Mike

推荐答案

好吧,我现在已经解决了我的问题,在一个hackish的方式,但是,是它的工作)。如果有人能改善我的解决方案,请让我知道。对于我的新的解决方案我现在用一个CustomFragmentStatePagerAdapter,但它不保存状态,像它应该和存储所有在列表中的片段。这可能会导致内存问题,如果用户有超过50个的碎片,像正常的FragmentPagerAdapter一样。这将是巨大的,如果有人能增加国家的事情回到了我的解决方案,而不删除我的修正。谢谢你。

Ok i've now solved my problem in a hackish way, but yeah it's working ;). If someone can improve my solution please let me know. For my new solution i now use a CustomFragmentStatePagerAdapter but it doesn't save the state like it should and stores all the Fragments in a list. This can cause a memory problem if the user has more than 50 fragments, like the normal FragmentPagerAdapter does. It would be great if someone can add the State-thing back to my solution without removing my fixes. Thanks.

因此​​,这里是我的 CustomFragmentStatePagerAdapter.java

So here's my CustomFragmentStatePagerAdapter.java

package com.tundem.webLab.Adapter;

import java.util.ArrayList;

import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

public abstract class CustomFragmentStatePagerAdapter extends PagerAdapter {
    private static final String TAG = "FragmentStatePagerAdapter";
    private static final boolean DEBUG = false;

    private final FragmentManager mFragmentManager;
    private FragmentTransaction mCurTransaction = null;

    public ArrayList<Fragment.SavedState> mSavedState = new ArrayList<Fragment.SavedState>();
    public ArrayList<Fragment> mFragments = new ArrayList<Fragment>();
    private Fragment mCurrentPrimaryItem = null;

    public CustomFragmentStatePagerAdapter(FragmentManager fm) {
        mFragmentManager = fm;
    }

    /**
     * Return the Fragment associated with a specified position.
     */
    public abstract Fragment getItem(int position);

    @Override
    public void startUpdate(ViewGroup container) {}

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        // If we already have this item instantiated, there is nothing
        // to do. This can happen when we are restoring the entire pager
        // from its saved state, where the fragment manager has already
        // taken care of restoring the fragments we previously had instantiated.

        // DONE Remove of the add process of the old stuff
        /* if (mFragments.size() > position) { Fragment f = mFragments.get(position); if (f != null) { return f; } } */

        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }

        Fragment fragment = getItem(position);
        if (DEBUG)
            Log.v(TAG, "Adding item #" + position + ": f=" + fragment);
        if (mSavedState.size() > position) {
            Fragment.SavedState fss = mSavedState.get(position);
            if (fss != null) {
                try // DONE: Try Catch
                {
                    fragment.setInitialSavedState(fss);
                } catch (Exception ex) {
                    // Schon aktiv (kA was das heißt xD)
                }
            }
        }
        while (mFragments.size() <= position) {
            mFragments.add(null);
        }
        fragment.setMenuVisibility(false);
        mFragments.set(position, fragment);
        mCurTransaction.add(container.getId(), fragment);

        return fragment;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        Fragment fragment = (Fragment) object;

        if (mCurTransaction == null) {
            mCurTransaction = mFragmentManager.beginTransaction();
        }
        mCurTransaction.remove(fragment);

        /*if (mCurTransaction == null) { mCurTransaction = mFragmentManager.beginTransaction(); } if (DEBUG) Log.v(TAG, "Removing item #" + position + ": f=" + object + " v=" + ((Fragment)
         * object).getView()); while (mSavedState.size() <= position) { mSavedState.add(null); } mSavedState.set(position, mFragmentManager.saveFragmentInstanceState(fragment));
         * mFragments.set(position, null); mCurTransaction.remove(fragment); */
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        Fragment fragment = (Fragment) object;
        if (fragment != mCurrentPrimaryItem) {
            if (mCurrentPrimaryItem != null) {
                mCurrentPrimaryItem.setMenuVisibility(false);
            }
            if (fragment != null) {
                fragment.setMenuVisibility(true);
            }
            mCurrentPrimaryItem = fragment;
        }
    }

    @Override
    public void finishUpdate(ViewGroup container) {
        if (mCurTransaction != null) {
            mCurTransaction.commitAllowingStateLoss();
            mCurTransaction = null;
            mFragmentManager.executePendingTransactions();
        }
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return ((Fragment) object).getView() == view;
    }

    @Override
    public Parcelable saveState() {
        Bundle state = null;
        if (mSavedState.size() > 0) {
            state = new Bundle();
            Fragment.SavedState[] fss = new Fragment.SavedState[mSavedState.size()];
            mSavedState.toArray(fss);
            state.putParcelableArray("states", fss);
        }
        for (int i = 0; i < mFragments.size(); i++) {
            Fragment f = mFragments.get(i);
            if (f != null) {
                if (state == null) {
                    state = new Bundle();
                }
                String key = "f" + i;
                mFragmentManager.putFragment(state, key, f);
            }
        }
        return state;
    }

    @Override
    public void restoreState(Parcelable state, ClassLoader loader) {
        if (state != null) {
            Bundle bundle = (Bundle) state;
            bundle.setClassLoader(loader);
            Parcelable[] fss = bundle.getParcelableArray("states");
            mSavedState.clear();
            mFragments.clear();
            if (fss != null) {
                for (int i = 0; i < fss.length; i++) {
                    mSavedState.add((Fragment.SavedState) fss[i]);
                }
            }
            Iterable<String> keys = bundle.keySet();
            for (String key : keys) {
                if (key.startsWith("f")) {
                    int index = Integer.parseInt(key.substring(1));
                    Fragment f = mFragmentManager.getFragment(bundle, key);
                    if (f != null) {
                        while (mFragments.size() <= index) {
                            mFragments.add(null);
                        }
                        f.setMenuVisibility(false);
                        mFragments.set(index, f);
                    } else {
                        Log.w(TAG, "Bad fragment at key " + key);
                    }
                }
            }
        }
    }
}

下面是我的正常的 FragmentAdapter.java

package com.tundem.webLab.Adapter;

import java.util.LinkedList;
import java.util.List;

import android.support.v4.app.FragmentManager;

import com.tundem.webLab.fragments.BaseFragment;
import com.viewpagerindicator.TitleProvider;

public class FragmentAdapter extends CustomFragmentStatePagerAdapter implements TitleProvider {
    public List<BaseFragment> fragments = new LinkedList<BaseFragment>();

    private int actPage;

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

    public void setActPage(int actPage) {
        this.actPage = actPage;
    }

    public void addItem(BaseFragment fragment) {
        // TODO if exists don't open / change to that tab
        fragments.add(fragment);
    }

    public BaseFragment getActFragment() {
        return getItem(getActPage());
    }

    public int getActPage() {
        return actPage;
    }

    @Override
    public BaseFragment getItem(int position) {
        if (position < getCount()) {
            return fragments.get(position);
        } else
            return null;
    }

    @Override
    public int getCount() {
        return fragments.size();
    }

    @Override
    public String getTitle(int position) {
        return fragments.get(position).getTitle();
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }
}

这也是我删除片段的方式。 (我知道这是不是只卸下摆臂多一点())。随意提高我的解决方案,也可以在某个适配器添加此code所以是的。这是给谁试图实现这个用户。我用这个在我的 TabHelper.java (负责处理如删除所有的标签操作类,添加...)

And this is the way i delete a Fragment. (I know it's a bit more than only .remove() ). Be free to improve my solution, you can also add this code somewhere in the adapter so yeah. It's up to the user who tries to implement this. I use this in my TabHelper.java (A class which handles all tab operations like delete, add, ...)

    int act = Cfg.mPager.getCurrentItem();
    Cfg.mPager.removeAllViews();
    Cfg.mAdapter.mFragments.remove(act);
    try {
        Cfg.mAdapter.mSavedState.remove(act);
    } catch (Exception ex) {/* Already removed */}
    try {
        Cfg.mAdapter.fragments.remove(act);
    } catch (Exception ex) {/* Already removed */}

    Cfg.mAdapter.notifyDataSetChanged();
    Cfg.mIndicator.notifyDataSetChanged();

CFG的说明。事情。我保存在CFG引用这些对象,类,所以我可以一直使用它们,而不需要特殊的Factory.java的...

Description of the Cfg. thing. I save the reference to those objects in a cfg, class so i can always use them without the need of a special Factory.java ...

呀。我希望我能够帮助。随意提高这一点,但让我知道这样我就可以提高我的code了。

Yeah. i hope i was able to help. Feel free to improve this, but let me know so i can improve my code too.

感谢。

如果我错过任何code让我知道。

If i missed any code let me know.

我以前的答案也适用,但只有当你有不同的片段。 FileFragment,WebFragment,...不,如果你使用这些fragmenttypes之一的两倍。

My old answer also works but only if you have different Fragments. FileFragment, WebFragment, ... Not if you use one of those fragmenttypes twice.

我得到了它的伪工作现在。这是一个非常肮脏的解决方案,我依然在寻找一个更好的。请帮忙。

I got it pseudo working for now. It's a really dirty solution and i'm still searching for a better one. Please help.

我改变了code,其中我删除选项卡这一个:

I changed the code, where i delete a tab to this one:

   public static void deleteActTab()
        {   
            //We set this on the indicator, NOT the pager
            int act = Cfg.mPager.getCurrentItem();
            Cfg.mAdapter.removeItem(act);
            List<BaseFragment> frags = new LinkedList<BaseFragment>();
            frags = Cfg.mAdapter.fragments;

            Cfg.mPager = (ViewPager)Cfg.act.findViewById(R.id.pager);
            Cfg.mPager.setAdapter(Cfg.mAdapter);
            Cfg.mIndicator.setViewPager(Cfg.mPager);

            Cfg.mAdapter.fragments = frags;

            if(act > 0)
            {
                Cfg.mPager.setCurrentItem(act-1);
                Cfg.mIndicator.setCurrentItem(act-1);
            }

            Cfg.mIndicator.notifyDataSetChanged();
        }

如果有人能改善这个code让我知道。如果有人能告诉我们这个问题真正的答案。请在这里添加它。还有谁遇到此问题很多很多人。我加的50声誉谁解决它的人。我还可以给谁解决了一个捐赠。

If someone can improve this code let me know. If someone can tell us the real answer for that problem. please add it here. There are many many people who experience this issue. I added a reputation of 50 for the one who solve it. I can also give a donation for the one who solve it.

感谢