ViewPager无法显示正确的图像

时间:2014-09-26 04:47:08

标签: android imageview android-viewpager

我的应用程序中有3个页面,我通过在屏幕上进行滑动来遍历。

整个应用程序只有1个ImageView共享3个页面/片段。 每个人都有自己的形象。

当我滑动到每个页面时出现问题。从第1页开始滑动 - > 2 - > 3并返回2 - > 1 - > 2,最后回到1,第1页的ImageView显示了第2页的ImageView。我不明白为什么会发生这种情况,即使我输入的各种日志清楚地显示我在正确的页面并且调用了正确的函数。

我已经用更短的版本替换了这个问题中的代码,但基本上也展示了相同的问题。这些是我从网站引用的代码,在搜索如何刷多页时我记不住了。

此项目的zip文件为here

这是MainActivity.java的代码,

package com.example.swiping;

import java.util.Locale;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity 
{
    static final int NUM_PAGE = 3;

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a {@link FragmentPagerAdapter}
     * derivative, which will keep every loaded fragment in memory. If this
     * becomes too memory intensive, it may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    public static ViewPager mViewPager;
    static ImageView ImgView1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(
                getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager); //This is from the activity_main.xml's one and only ViewPager
        mViewPager.setAdapter(mSectionsPagerAdapter);
    }


    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class
            // below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show x number of pages.
            return NUM_PAGE;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            case 2:
                return getString(R.string.title_section3).toUpperCase(l);
            }
            return null;
        }
    }//SectionsPagerAdapter

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView
        (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
        {
            View rootView = inflater.inflate
                    (R.layout.fragment_main, container,false);
            TextView textView = (TextView) rootView.findViewById(R.id.section_label);
            textView.setText
            (Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));

            ImgView1 = (ImageView) rootView.findViewById(R.id.imageView1);

            Log.i("Swiping", "Current Item is " + mViewPager.getCurrentItem());

            mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() 
            {
                @Override
                public void onPageSelected(int position)
                {   
                    Log.i("Swiping", "Current Item is " + mViewPager.getCurrentItem());

                    if(mViewPager.getCurrentItem() == 0)
                    {
                        ImgView1.setImageDrawable(getResources().getDrawable(R.drawable.qnmark));
                    }
                    else if(mViewPager.getCurrentItem() == 1)
                    {
                        ImgView1.setImageDrawable(getResources().getDrawable(R.drawable.genieus));
                    }
                    else if(mViewPager.getCurrentItem() == 2)
                    {
                        ImgView1.setImageDrawable(getResources().getDrawable(R.drawable.community));
                    }
                }
            });//setOnPageChangeListener

            return rootView;
        }//onCreateView
    }//PlaceholderFragment

}//MainActivity

1 个答案:

答案 0 :(得分:0)

我通过删除“setOnPageChangeListener()”解决了这个问题,并改为使用了bundle。 这是代码:

package com.example.swiping;

import java.util.Locale;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity 
{
    static final int NUM_PAGE = 3;

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a {@link FragmentPagerAdapter}
     * derivative, which will keep every loaded fragment in memory. If this
     * becomes too memory intensive, it may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    public static ViewPager mViewPager;
    static ImageView ImgView1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(
                getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager); //This is from the activity_main.xml's one and only ViewPager
        mViewPager.setAdapter(mSectionsPagerAdapter);
    }


    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class
            // below).
            return PlaceholderFragment.newInstance(position + 1);
        }

        @Override
        public int getCount() {
            // Show x number of pages.
            return NUM_PAGE;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
            case 0:
                return getString(R.string.title_section1).toUpperCase(l);
            case 1:
                return getString(R.string.title_section2).toUpperCase(l);
            case 2:
                return getString(R.string.title_section3).toUpperCase(l);
            }
            return null;
        }
    }//SectionsPagerAdapter

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView
        (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
        {
            View rootView = inflater.inflate
                    (R.layout.fragment_main, container,false);

            Bundle bundle = getArguments();

            if( bundle != null )
            {
                int PageNum = bundle.getInt(ARG_SECTION_NUMBER);

                TextView textView = (TextView) rootView.findViewById(R.id.section_label);
                textView.setText(Integer.toString(PageNum));

                ImgView1 = (ImageView) rootView.findViewById(R.id.imageView1);

                if(PageNum == 1)
                {
                    ImgView1.setImageDrawable(getResources().getDrawable(R.drawable.qnmark));
                }
                else if(PageNum == 2)
                {
                    ImgView1.setImageDrawable(getResources().getDrawable(R.drawable.genieus));
                }
                else if(PageNum == 3)
                {
                    ImgView1.setImageDrawable(getResources().getDrawable(R.drawable.community));
                }

            }

            return rootView;
        }//onCreateView
    }//PlaceholderFragment

}//MainActivity

Credits用于在实施ViewPager时观看CodingBits here中的一个Android教程视频。显然,决定要显示哪些图像和文本而不是在页面发生变化时动态更改它们会更加稳定。

我对视频教程的观察是,每次在getItem()中创建一个片段时,都会将包含要显示的图像和要使用的描述(使用某种形式的id)的包放入包中。然后将该包添加到片段中。

在onCreateView()中,在检索它的值之前,首先检查该包是否为null。然后使用这些值来设置ImageView和文本描述。

但是,我仍然很好奇为什么setOnPageChangeListener()无法正常工作或者我没有正确使用它。如果有人能给我一个解释,我会非常感激。