如何使用AsyncTask在PaperAdapter中显示URL图像

时间:2014-06-19 03:03:03

标签: android

最后,我更改了我的代码并使用了univeral-image-loader库

我使用paperadapter来显示代码的url图像,它工作正常。

@Override
public Object instantiateItem(final ViewGroup container, final int position) {
Drawable[] imageDrawable = new Drawable[3];
for (int i = 0; i < 3; i++) {
imageDrawable[i] = LoadImageFromWebOperations(server_url+ image_name.replace(" ","")+ "_0" +String.valueOf(i + 1) + ".jpg");
}
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageDrawable(imageDrawable[position]);
container.addView(imageView, 0);
return imageView;
}

但我想使用asynctask来执行此操作,例如代码

@Override
public Object instantiateItem(final ViewGroup container, final int position) {

    AsyncTask<String, Void, Drawable[]> loadingImage = new AsyncTask<String, Void, Drawable[]>(){

        @Override
        protected Drawable[] doInBackground(String... params) {
            // TODO Auto-generated method stub
            Drawable imageDrawable[] = new Drawable[3];
            for (int i = 0; i < 3; i++) {
                imageDrawable[i] = LoadImageFromWebOperations(server_url
                        + image_name.replace(" ","")+ "_0" + String.valueOf(i + 1) + ".jpg");
                System.out.println("doInBackground="+position);
            }
            return imageDrawable;
        }
        @Override
        protected void onPostExecute(Drawable[] result) {
            System.out.println("onPostExecute="+position);
            imageView = new ImageView(getBaseContext());
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setImageDrawable(result[position]);
            container.addView(imageView, 0);
                }
            });
        }

    }; loadingImage.execute();
    return imageView;
}

它不能正常工作。我发现位置“1”为空而没有图像,但位置0和2不为空,等待一些建议,谢谢!

1 个答案:

答案 0 :(得分:0)

这是所有代码:

 public class ProductDetailActivity1 extends FragmentActivity {

        ImageAdapter mAdapter;
        ViewPager mPager;
        CirclePageIndicator mIndicator;
        private String server_url;
        ImageView imageView;    
      protected ScrollView mScrollView;

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

            mScrollView = (ScrollView)findViewById(R.id.card_scrollview);


            getActionBar();
            getActionBar().setHomeButtonEnabled(true);
            getActionBar().setDisplayHomeAsUpEnabled(true);
            getActionBar().setDisplayShowTitleEnabled(true);
            getActionBar().setTitle(R.string.product_detail);

            Intent intent = getIntent();
            server_url = intent.getStringExtra("SERVER_URL");

            mAdapter = new ImageAdapter(getApplicationContext());
            mPager = (ViewPager) findViewById(R.id.imageViewpager);
            mPager.setAdapter(mAdapter);


            mIndicator = (CirclePageIndicator) findViewById(R.id.indicator);
            mIndicator.setViewPager(mPager);
            mIndicator.setFillColor(0xFFFFFFFF);
            mIndicator.setStrokeColor(0xFFFFFFFF);
            mIndicator.setStrokeWidth(1);
            mIndicator.setRadius(6 * getResources().getDisplayMetrics().density);
            ((CirclePageIndicator) mIndicator).setSnap(true);
            mIndicator
                    .setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                        @Override
                        public void onPageSelected(int position) {
                        }

                        @Override
                        public void onPageScrolled(int position,
                                float positionOffset, int positionOffsetPixels) {
                        }

                        @Override
                        public void onPageScrollStateChanged(int state) {
                        }
                    });
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {

            switch (item.getItemId()) {
            case android.R.id.home:
                Intent intent = new Intent(ProductDetailActivity1.this,
                        com.wangrui.ams.MainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
            }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.product_detail, menu);
            return true;
        }

        public class ImageAdapter extends PagerAdapter {
            private Context mContext;
            private Drawable[] imageDrawable  = new Drawable[3];;

            public ImageAdapter(Context cx) {
                mContext = cx.getApplicationContext();
            }

            @Override
            public Object instantiateItem(final ViewGroup container, final int position) {
                AsyncTask<Void, Void, Drawable[]> loadingImage = new AsyncTask<Void, Void, Drawable[]>(){

                    @Override
                    protected Drawable[] doInBackground(Void... params) {
                        // TODO Auto-generated method stub  

                        for (int i = 0; i < 3; i++) {
                            imageDrawable[i] = LoadImageFromWebOperations(server_url
                                    + image_name.replace(" ","")+ "_0" + String.valueOf(i + 1) + ".jpg");
                            System.out.println("position="+i);
                        }
                        return imageDrawable;
                    }
                    @Override
                    protected void onPostExecute(Drawable[] result) {
                        imageView = new ImageView(mContext);
                        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    imageView.setImageDrawable(result[position]);
                        mPager.getAdapter().notifyDataSetChanged();
                         ((ViewPager) container).addView(imageView, position);

                    }               
                }; loadingImage.execute();

                return imageView;
            }

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

            @Override
            public boolean isViewFromObject(final View view, final Object object) {
                // TODO Auto-generated method stub
                //return arg0 == (View) arg1;
                return view == ((ImageView) object);
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                container.removeView((ImageView) object);
            }

        }

        private void showAlertMessage(String msg){

            SuperToast superToast = new SuperToast(getApplicationContext());
            superToast.setAnimations(SuperToast.Animations.FLYIN);
            superToast.setDuration(SuperToast.Duration.LONG);
            superToast.setBackground(SuperToast.Background.RED);
            superToast.setTextSize(SuperToast.TextSize.EXTRA_SMALL);
            superToast.setText(msg);
            superToast.show();
        }

        private Drawable LoadImageFromWebOperations(String url) {
            try {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                        .permitAll().build();
                StrictMode.setThreadPolicy(policy);
                InputStream is = (InputStream) new URL(url).getContent();
                Drawable d = Drawable.createFromStream(is, "src name");
                return d;
            } catch (Exception e) {
                System.out.println("Exc=" + e);
                return null;
            }
        }
    }