viewpager无法正常工作

时间:2013-12-29 20:08:45

标签: android android-viewpager

我已经使用了下面的代码并且它在每次滑动之后一直加载图像。而且第一次图像从未在第一次显示但是在我滑到列表末尾然后返回然后加载。我的实现是正确的,因为我失败了吗?代码正在运行,但它并不完美。我非常感谢有关此代码或主题的任何帮助。谢谢提前。

MainActivity:

public class MainActivity extends Activity {

      final String[] page_titles = new String[]{"Title1", "Title2", "Title3", "Title4", "Title5"};
        //this will go the description TextView
            final String[] desc = new String[]{
                "desc1",
                "desc2",
                "desc3",
                "desc4",
                "desc5"
        };


            ImageView im;

            String[] urls = {
                    "1.jpg",
                    "2.jpg",
                    "3.jpg",
                    "4.jpg",
            };

    ViewPager vp;

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

         //Instantiating the adapter
        myAdaptertest1 mAdapter = new myAdaptertest1(this);

        vp=(ViewPager)findViewById(R.id.pager);

        vp.setAdapter(mAdapter);

        ////////




    }

适配器:

    private class myAdaptertest1 extends PagerAdapter{

        Context context;

        public myAdaptertest1(Context c){
            this.context = c;
        }

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

        @Override
        public boolean isViewFromObject(View v, Object o) {
            // TODO Auto-generated method stub
              return v.equals(o);
        }





        public Object instantiateItem(View pager, int position) {
            final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View vi = inflater.inflate(R.layout.page, null, false);

            TextView title = (TextView)vi.findViewById(R.id.tvTitle);
            TextView description = (TextView) vi.findViewById(R.id.tvdesc);

             im = (ImageView)vi.findViewById(R.id.imageView1);


            title.setText(page_titles[position]);
            description.setText(desc[position]);

                       String rt = urls[position];

                        MyTask task = new MyTask();
                        task.execute(rt); 
            //This is very important
            ( (ViewPager) pager ).addView( vi, 0 );

            return vi;
        }

        @Override
        public void destroyItem(View pager, int position, Object view) {
            ((ViewPager) pager).removeView((View) view);
        }


    }

MyTask:

    private class MyTask extends AsyncTask<String, Void, Drawable> {

         ProgressDialog pd;


         @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();


            pd = ProgressDialog.show(MainActivity.this, "Working..", "Getting image", true, false);
        }

        protected Drawable doInBackground(String... url) {
                try {
                    InputStream is = (InputStream) new URL(url[0]).getContent();
                    Drawable d = Drawable.createFromStream(is, "src name");
                    return d;
                } catch (Exception e) {
                    System.out.println("Exception = " + e);
                    return null;
                }
         }

         protected void onProgressUpdate(Void... progress) {
         }

         protected void onPostExecute(Drawable result) {
             /* Image loaded...*/
             pd.dismiss();

             im.setImageDrawable(result);

         }
    }

}

logcat的:

 FATAL EXCEPTION: main
 Process: com.example., PID: 26715
 java.lang.IllegalStateException: ImageLoader must be init with configuration before using
    at com.nostra13.universalimageloader.core.ImageLoader.checkConfiguration(ImageLoader.java:560)
    at com.nostra13.universalimageloader.core.ImageLoader.displayImage(ImageLoader.java:206)
    at com.nostra13.universalimageloader.core.ImageLoader.displayImage(ImageLoader.java:284)
    at com.example..MainActivity$myAdaptertest1.instantiateItem(MainActivity.java:112)
    at android.support.v4.view.PagerAdapter.instantiateItem(PagerAdapter.java:110)
    at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:832)
    at android.support.v4.view.ViewPager.populate(ViewPager.java:982)
    at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
    at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
    at android.view.View.measure(View.java:16497)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
    at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
    at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
    at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
    at android.view.View.measure(View.java:16497)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at android.view.View.measure(View.java:16497)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
    at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:327)
    at android.view.View.measure(View.java:16497)
    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
    at android.view.View.measure(View.java:16497)
    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916)
    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113)
    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295)
    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
    at android.view.Choreographer.doCallbacks(Choreographer.java:574)
    at android.view.Choreographer.doFrame(Choreographer.java:544)
    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:136)
    at android.app.ActivityThread.main(ActivityThread.java:5017)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
    at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:2)

问题是每当instantiateItem被调用im更改时,当你的任务完成第一项时,instantiateItem被调用第二项或第三项,因此你的im变量有引用它,所以当你调用im.setImageDrawable()时,它会被错误的imageview对象调用。

尝试使用通用图像加载器而不是盯着自己的任务

参考:

https://github.com/nostra13/Android-Universal-Image-Loader

这样可以确保每次滑动时都不会加载图像

在项目中添加库并按以下方式更改代码:

private class myAdaptertest1 extends PagerAdapter{

    Context context;
    ImageLoader imageLoader;
    public myAdaptertest1(Context c){
        this.context = c;

   DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
    .cacheInMemory(true)
    .cacheOnDisc(true)
    .build();
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
    .defaultDisplayImageOptions(defaultOptions)
    .build();
       imageLoader=  ImageLoader.getInstance();
        imageLoader.init(config);
    }

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

    @Override
    public boolean isViewFromObject(View v, Object o) {
        // TODO Auto-generated method stub
          return v.equals(o);
    }





    public Object instantiateItem(View pager, int position) {
        final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View vi = inflater.inflate(R.layout.page, null, false);

        TextView title = (TextView)vi.findViewById(R.id.tvTitle);
        TextView description = (TextView) vi.findViewById(R.id.tvdesc);

         im = (ImageView)vi.findViewById(R.id.imageView1);


        title.setText(page_titles[position]);
        description.setText(desc[position]);

                   String rt = urls[position];
        imageLoader.displayImage(rt, im);//<---here just call this function
        //This is very important
        ( (ViewPager) pager ).addView( vi, 0 );

        return vi;
    }

    @Override
    public void destroyItem(View pager, int position, Object view) {
        ((ViewPager) pager).removeView((View) view);
    }