PagerAdapter类被多次调用

时间:2013-02-15 10:46:22

标签: android android-viewpager android-pageradapter

我正在开发一个包含ViewPager视图的应用程序,     我创建了一个PagerAdapter,它有视图,PagerAdapter的instantiateItem()方法在create()中被调用两次我不知道为什么,任何人都可以帮我这个吗?

这是我的代码,

         View PagerView;
        MyPagerAdapter adapter;
        ViewPager pager;

            adapter = new MyPagerAdapter();     
    pager.setAdapter(adapter);
    pager.setCurrentItem(0);

public class MyPagerAdapter extends PagerAdapter {

        @Override
        public Object instantiateItem(final View collection, final int position) {
            Log.d("Inside", "Pager");
            PagerView = new View(collection.getContext());
            LayoutInflater inflater = (LayoutInflater) collection.getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            PagerView = inflater.inflate(R.layout.tablemenu, null, false);
            tbMenuDetails = (TableLayout) PagerView
                    .findViewById(R.id.Menutable1);
            scrollview = (ScrollView) PagerView.findViewById(R.id.scrollView1);
            tbMenuDetails.removeAllViews();
            removeTableRows();
            createTableLayout(position);
            String str[][] = datasource.GetSubMenuDetailsFromMenuId(MenuIdlst
                    .get(position).trim());
            Log.d("Str", "" + str.length);
            for (int i = 0; i < str.length; i++) {
                addRows(str[i][1], str[i][2], str[i][0], str[i][3], position);
                Log.d("Message", "Pos   " + position + "    SubMenuName" + str[i][2]
                        + " SubMenuId" + " " + str[i][0] + " TypeID" + "    "
                        + str[i][3]);
            }

            // View view = inflater.inflate(resId, null);
            ((ViewPager) collection).addView(PagerView, 0);

            return PagerView;
        }

        @Override
        public void destroyItem(final View arg0, final int arg1,
                final Object arg2) {
            ((ViewPager) arg0).removeView((View) arg2);

        }

        @Override
        public boolean isViewFromObject(final View arg0, final Object arg1) {
            return arg0 == ((View) arg1);

        }

        @Override
        public void finishUpdate(View arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {
            // TODO Auto-generated method stub

        }

        @Override
        public Parcelable saveState() {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public void startUpdate(View arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return MenuIdlst.size();
        }

    }

请帮忙

5 个答案:

答案 0 :(得分:5)

如果您决定使用片段,请不要实施PagerAdapter。相反,请扩展FragmentPagerAdapterFragmentStatePagerAdapter

private class MyPagerAdapter extends FragmentStatePagerAdapter {
    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public int getCount() {
        return NUMBER_OF_PAGES_IN_PAGER;
    }

    @Override
    public Fragment getItem(int position) {
        // Implement the static method newInstance in MyFragment.java yourself.
        // It should return you a brand new instance of MyFragment, basically using
        // the code you had in your original instantiateItem method.
        return MyFragment.newInstance(position, ... etc ...); 
    }
}

然后在你的活动中:

myPagerAdapter = new MyPagerAdapter(getFragmentManager());
// or myPagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
myViewPager.setAdapter(myPagerAdapter);

要获取有关如何使用Fragments和ViewPagers的更多信息: https://developer.android.com/reference/android/app/Fragment.html https://developer.android.com/reference/android/support/v4/view/ViewPager.html https://developer.android.com/reference/android/support/v4/app/FragmentStatePagerAdapter.html

答案 1 :(得分:4)

默认情况下,ViewPager会在当前页面之前/之前预加载一页(如果有的话)。你没有说它是否被称为相同或不同的位置。

答案 2 :(得分:3)

ViewPager.setOffscreenpageLimit(int)的最小值为1.您可以从source code for ViewPager看到这一点:

private static final int DEFAULT_OFFSCREEN_PAGES = 1;

...

/**
     * Set the number of pages that should be retained to either side of the
     * current page in the view hierarchy in an idle state. Pages beyond this
     * limit will be recreated from the adapter when needed.
     *
     * <p>This is offered as an optimization. If you know in advance the number
     * of pages you will need to support or have lazy-loading mechanisms in place
     * on your pages, tweaking this setting can have benefits in perceived smoothness
     * of paging animations and interaction. If you have a small number of pages (3-4)
     * that you can keep active all at once, less time will be spent in layout for
     * newly created view subtrees as the user pages back and forth.</p>
     *
     * <p>You should keep this limit low, especially if your pages have complex layouts.
     * This setting defaults to 1.</p>
     *
     * @param limit How many pages will be kept offscreen in an idle state.
     */
    public void setOffscreenPageLimit(int limit) {
        if (limit < DEFAULT_OFFSCREEN_PAGES) {
            Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to " +
                    DEFAULT_OFFSCREEN_PAGES);
            limit = DEFAULT_OFFSCREEN_PAGES;
        }
        if (limit != mOffscreenPageLimit) {
            mOffscreenPageLimit = limit;
            populate();
        }
    }

如果您尝试将其设置为零,则应在Logcat中看到警告。

下限为1是一个很好的理由。当您滚动寻呼机时,需要已经加载相邻页面 - 否则您将看不到下一页的任何内容。如果您设法强制屏幕外页面限制为零,那么当您从第一页滚动到第二页时,您可能只会看到一个黑色的空白页面。如果您在开头创建第一页和第二页时遇到特定问题,请尝试定位并修复该问题。

答案 3 :(得分:2)

在寻呼机中为每个视图使用片段。

onCreate()的{​​{1}}方法中编写以下代码。

FragmentActivity

样本片段定义:

List<Fragment> fragments = new Vector<Fragment>();

//for each fragment you want to add to the pager
Bundle page = new Bundle();
page.putString("url", url);
fragments.add(Fragment.instantiate(this,MyFragment.class.getName(),page));

//after adding all the fragments write the below lines

this.mPagerAdapter  = new PagerAdapter(super.getSupportFragmentManager(), fragments);

mPager.setAdapter(this.mPagerAdapter);

每当我需要使用public class MyFragment extends Fragment { public static MyFragment newInstance(String imageUrl) { final MyFragment mf = new MyFragment (); final Bundle args = new Bundle(); args.putString("somedata", "somedata"); mf.setArguments(args); return mf; } public MyFragment() {} @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String data = getArguments().getString("somedata"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate and locate the main ImageView final View v = inflater.inflate(R.layout.my_fragment_view, container, false); //... return v; } 时,我都会使用此方法。希望这可以帮助。我无法弄清楚为什么你的实例化方法是从你提供的信息中被调用两次。

答案 4 :(得分:-1)

对isViewFromObject()方法有必要改变。这是非常重要的,在它的文档中说"This method is required for a PagerAdapter to function properly."

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

您可以查看here