2012-11-14 25 views
1

我有以下類來顯示一些圖像... 我已經實現了將圖像下載到SD卡的能力。 如果我通過他們一切都很好(圖片+標題顯示),但如果我開始在某個圖像的下載,使用另一個圖像(另一個圖像)的另一個網址,所以我不知何故認爲我的ViewPager沒有正確更新或什麼的。ViewPager使用錯誤的條目

這是我的課:

public class ImagePagerActivity extends BaseActivity { 

private ViewPager pager; 

LinearLayout buttonBar; 
TextView txtTitle; 

String urlOfImageToDownload; 

public static final int DIALOG_DOWNLOAD_PROGRESS = 0; 
private ProgressDialog mProgressDialog; 

private static DisplayImageOptions options; 

ImageView imageView; 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.ac_image_pager); 
    Bundle bundle = getIntent().getExtras(); 
    String[] imageUrls = bundle.getStringArray(Extra.IMAGES); 
    String[] imageTitles = bundle.getStringArray(Extra.TITLES); 
    int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0); 

    options = new DisplayImageOptions.Builder() 
      .cacheOnDisc().showImageForEmptyUri(R.drawable.no_image) 
      .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) 
      .build(); 

    pager = (ViewPager) findViewById(R.id.pager); 
    pager.setAdapter(new ImagePagerAdapter(imageUrls, imageTitles)); 
    pager.setCurrentItem(pagerPosition); 
} 

@Override 
public boolean onPrepareOptionsMenu(Menu menu) { 
    if (imageView.getDrawable() == null) 
     menu.getItem(0).setEnabled(false); 
    return true; 
} 

public boolean onCreateOptionsMenu(Menu menu) { 
    menu.add(0, 0, 0, 
      getString(R.string.save_image)).setIcon(android.R.drawable.ic_menu_save); 
    return true; 
} 

public boolean onOptionsItemSelected(MenuItem item) { 
    switch (item.getItemId()) { 
     case 0: 
      Random randomGenerator = new Random(); 
      int randomInt = 0; 
      for (int idx = 1; idx <= 10; ++idx) { 
       randomInt = randomGenerator.nextInt(100000); 
      } 

      imageView.setDrawingCacheEnabled(true); 
      Bitmap b = imageView.getDrawingCache(); 
      try { 
       b.compress(CompressFormat.JPEG, 100, 
         new 
         FileOutputStream(Environment.getExternalStorageDirectory() 
           .getPath() + "/DCIM/image" + randomInt + ".jpg")); 
       Crouton.makeText(ImagePagerActivity.this, 
         "Bild erfolgreich gespeichert", 
         Style.INFO) 
         .show(); 
      } catch (FileNotFoundException e) { 
       Crouton.makeText(ImagePagerActivity.this, 
         "Fehler beim speichern von Datei", 
         Style.ALERT) 
         .show(); 
      } 

      startDownload(); 

      return true; 
    } 
    return false; 
} 

private void startDownload() { 
    String url = urlOfImageToDownload; 
    Log.e(MainActivity.LOG_TAG, "url=" + urlOfImageToDownload); 
    new DownloadFileAsync().execute(url); 
} 

@Override 
protected Dialog onCreateDialog(int id) { 
    switch (id) { 
     case DIALOG_DOWNLOAD_PROGRESS: 
      mProgressDialog = new ProgressDialog(this); 
      mProgressDialog.setMessage(getString(R.string.downloading_image)); 
      mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
      mProgressDialog.setCancelable(false); 
      mProgressDialog.show(); 
      return mProgressDialog; 
     default: 
      return null; 
    } 
} 

@Override 
protected void onStop() { 
    imageLoader.stop(); 
    super.onStop(); 
} 

private class ImagePagerAdapter extends PagerAdapter { 

    private String[] images; 
    private String[] titles; 
    private LayoutInflater inflater; 

    ImagePagerAdapter(String[] images, String[] imageTitles) { 
     this.images = images; 
     this.titles = imageTitles; 
     inflater = getLayoutInflater(); 
    } 

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

    @Override 
    public void finishUpdate(View container) { 
    } 

    @Override 
    public int getCount() { 
     return images.length; 
    } 

    @Override 
    public Object instantiateItem(View view, int position) { 
     final FrameLayout imageLayout = (FrameLayout) inflater.inflate(
       R.layout.item_pager_image, null); 
     imageView = (ImageView) imageLayout 
       .findViewById(R.id.image); 
     final ProgressBar spinner = (ProgressBar) imageLayout 
       .findViewById(R.id.loading); 
     txtTitle = (TextView) imageLayout.findViewById(R.id.txtTitle); 

     urlOfImageToDownload = images[position]; 

     buttonBar = (LinearLayout) imageLayout.findViewById(R.id.buttonBar); 

     txtTitle.setText(titles[position]); 

     imageLoader.displayImage(images[position], imageView, options, 
       new ImageLoadingListener() { 
        @Override 
        public void onLoadingStarted() { 
         spinner.setVisibility(View.VISIBLE); 
        } 

        @Override 
        public void onLoadingFailed(FailReason failReason) { 
         switch (failReason) { 
          case IO_ERROR: 
           break; 
          case OUT_OF_MEMORY: 
           break; 
          case UNKNOWN: 
           break; 
         } 

         spinner.setVisibility(View.GONE); 
         imageView.setImageResource(android.R.drawable.ic_delete); 
        } 

        @Override 
        public void onLoadingComplete(Bitmap bm) { 
         spinner.setVisibility(View.GONE); 
        } 

        @Override 
        public void onLoadingCancelled() { 
         spinner.setVisibility(View.GONE); 
        } 
       }); 

     ((ViewPager) view).addView(imageLayout, 0); 
     return imageLayout; 
    } 

    @Override 
    public boolean isViewFromObject(View view, Object object) { 
     return view.equals(object); 
    } 

    @Override 
    public void restoreState(Parcelable state, ClassLoader loader) { 
    } 

    @Override 
    public Parcelable saveState() { 
     return null; 
    } 

    @Override 
    public void startUpdate(View container) { 
    } 

} 

class DownloadFileAsync extends AsyncTask<String, String, String> { 

    @SuppressWarnings("deprecation") 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     showDialog(DIALOG_DOWNLOAD_PROGRESS); 
    } 

    @Override 
    protected String doInBackground(String... aurl) { 
     int count; 

     try { 

      URL url = new URL(aurl[0]); 
      URLConnection conexion = url.openConnection(); 
      conexion.connect(); 

      int lenghtOfFile = conexion.getContentLength(); 

      Random rand = new Random(); 
      int randomNumber = rand.nextInt(100000); 

      InputStream input = new BufferedInputStream(url.openStream()); 
      OutputStream output = new FileOutputStream(
        "sdcard/nature_" + randomNumber + ".jpg"); 

      byte data[] = new byte[1024]; 

      long total = 0; 

      while ((count = input.read(data)) != -1) { 
       total += count; 
       publishProgress("" + (int) ((total * 100)/lenghtOfFile)); 
       output.write(data, 0, count); 
      } 

      output.flush(); 
      output.close(); 
      input.close(); 
     } catch (Exception e) { 
     } 
     return null; 

    } 

    protected void onProgressUpdate(String... progress) { 
     mProgressDialog.setProgress(Integer.parseInt(progress[0])); 
    } 

    @Override 
    protected void onPostExecute(String unused) { 
     dismissDialog(DIALOG_DOWNLOAD_PROGRESS); 
     Crouton.makeText(ImagePagerActivity.this, 
       getString(R.string.image_saved), 
       Style.CONFIRM) 
       .show(); 
    } 
    } 
} 

感謝您的幫助!

回答

1

問題:

的用戶第一次看的ViewPager的圖像,instantiateItem(..)該圖像將被調用,現場urlOfImagetoDownload將被設置爲正確的URL

urlOfImageToDownload = images[position]; 

然而如果用戶現在返回到他已經看到的圖像已經實例化,則instantiateItem(...)而不是被調用,並且urlOfImageToDownload將保存錯誤的URL(上一圖像) 。

解決方案:

您可以使用ViewPager#getCurrentItem()檢索當前圖像的索引,然後使用該索引與images[]得到正確的URL當用戶點擊下載。

+0

非常好的答案非常感謝! 也是一個很好的解釋。謝謝! – user754730

+0

@ user754730很高興幫助:) –