简体   繁体   中英

All pages in android ViewPager are shown in first slide

I used android android.support.v4.view.ViewPager in my layout with a custom PagerAdapter . I defined my adapter in this way (simplified):

private final PagerAdapter mPagerAdapter= new PagerAdapter() {

    @Override
    public void destroyItem(View v, int arg1, Object o) {
        ((ViewPager) v).removeView((View) o);
    }

    @Override
    public boolean isViewFromObject(View v, Object o) {
        return o == ((View) o);
    }

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

    public Object instantiateItem(View collection, final int position) {
        LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View view = inflater.inflate(R.layout.single_page, null);
        final String name;
        TextView pageName = (TextView) view.findViewById(R.id.tvPageName);
        switch (position) {
        case 0:
            name = "page 1";
            break;
        case 1:
            name = "page 2";
            break;
        default:
            name = "";
        }
        pageName.setText(name);
        ((ViewPager) collection).addView(view, 0);

        return view;
    }
};

single_page is a layout that is made up with a text view( tvPageName ) wrapped in a LinearLayout .

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tvPageName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name" />

</LinearLayout>

Result looks like this: 布局彼此堆叠

I tried using two different layouts for each page but result was The same.

A part of layout xml:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_horizontal"
    android:orientation="vertical" >

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <android.support.v4.view.ViewPager
            android:id="@+id/pages"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="#ffeedd" />
    </FrameLayout>
</LinearLayout>

Your implementation of isViewFromObject() is wrong. The current implementation will always return true , so your PagerAdapter won't work correctly.

You need it to be

@Override
public boolean isViewFromObject(View v, Object o) {
    return v == o;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM