查看寻呼机在滑动时显示相同的图像

时间:2018-02-14 01:51:42

标签: java android arraylist hashmap android-viewpager

我有一个相对布局,其中包含一个viewpager,可以让我滑动从我的Web服务中获取的图像。然后将获取的图像存储在包含HashMap的ArrayList中。我已经记录了来自Web服务的提取部分,并且日志表明我确实正在获取不同的图像。但是,每当我从图像滑动到图像时,viewpager都会显示相同的图像,该图像始终是最后保存的图像。我已经在寻呼机适配器中记录了图像的ArrayList,似乎我得到了正确的arraylist大小但是我得到了所有大小的相同位图。

这是我的PagerAdapter类:

public class ImageAdapter extends PagerAdapter {
    private LayoutInflater layoutInflater;
    private Context context;
    private ArrayList<HashMap<String, Object>> images;

    public ImageAdapter(Context context, ArrayList<HashMap<String, Object>> images) {
        this.context = context;
        this.images = images;
        layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View view = layoutInflater.inflate(R.layout.view_pager_image_video, null);
        RelativeLayout rlAttach = (RelativeLayout) view.findViewById(R.id.rl_attach);
        ImageView imgAttach = (ImageView) view.findViewById(R.id.img_attach);
        VideoView vvAttach = (VideoView) view.findViewById(R.id.vv_attach);
        LinearLayout llOverlay = (LinearLayout) view.findViewById(R.id.ll_video_overlay);
        ProgressBar pBar = (ProgressBar) view.findViewById(R.id.pBar);
        LinearLayout llUnsupportFile = (LinearLayout) view.findViewById(R.id.ll_unsupport_file);

        Log.d(TAG, "image: " + images.size() + " " + images);
        Bitmap image = (Bitmap) images.get(position).get("image");
        image = CommonUtilities.checkBitmapRotation(bmp);

        imgAttach.setVisibility(View.VISIBLE);
        vvAttach.setVisibility(View.GONE);
        llOverlay.setVisibility(View.GONE);
        llUnsupportFile.setVisibility(View.GONE);
        imgAttach.setImageBitmap(image);
        pBar.setVisibility(View.GONE);

        setPreviewClick(imgAttach, position, rlAttach);

        container.addView(view);
        return view;
    }

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

    @Override
    public boolean isViewFromObject(View view, Object obj) {
        return view == obj;
    }

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

这是我设置适配器并设置notifidydatasetchange的地方:

  if (galleryList.size() > 0) {
                    llNoGallery.setVisibility(View.GONE);
                    rlHasGallery.setVisibility(View.VISIBLE);
                    pbGallery.setVisibility(View.GONE);
                    vpGallery.setVisibility(View.VISIBLE);
                    tvPageCount.setVisibility(View.VISIBLE);

                    mImageAdapter = new ImageAdapter(getActivity(), galleryList);

                    for (HashMap getList : galleryList) {
                        Log.d(TAG, "onMe: " + getList.toString());
                    }
                    vpGallery.setAdapter(mImageAdapter);
                    vpGallery.addOnPageChangeListener(viewPagerPageChangeListener);
                    vpGallery.setOffscreenPageLimit(galleryList.size());
                     mImageAdapter.notifyDataSetChanged();

                    tvPageCount.setText("1/" + galleryList.size());
                } else {
                    rlHasGallery.setVisibility(View.GONE);
                    llNoGallery.setVisibility(View.VISIBLE);
                }

这是保存提取给arraylist的图像的功能:

private void saveImagesToArrayList(String photo) {
    bmp = null;

    if (!photo.isEmpty()) {
        bmp = imageLoader.loadImageSync(photo);

        // tmp hashmap for single image
        HashMap<String, Object> hmImage = new HashMap<String, Object>();
        // adding each child node to HashMap key => value
        hmImage.put("image", bmp);

        galleryList.add(hmImage);

        // tmp hashmap for single image
        HashMap<String, Object> hmImageInString = new HashMap<String, Object>();
        // adding each child node to HashMap key => value
        hmImageInString.put("image", photo);

        galleryListInString.add(hmImageInString);
    }


}

这是我的ViewPagerChangeListener,它显示了图片被转换到的位置:

 ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {

    @Override
    public void onPageSelected(int position) {
        tvPageCount.setText(position + 1 + "/" + (galleryList.size()));
    }

    @Override
    public void onPageScrolled(int pos, float arg1, int arg2) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
};

这里我有setPreviewClick方法通过意图全屏打开图像。此处显示的图像在此处是正确的,在滑动时显示不同的图像。

  private void setPreviewClick(View view, int imagePosition, RelativeLayout rlAttach) {
    final int mPosition = imagePosition;

    rlAttach.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            intentViewActivity(mPosition);
        }
    });

    ImageView mImg = (ImageView) view;
    mImg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            intentViewActivity(mPosition);
        }
    });

}

intentViewActivity方法如下:

 public void intentViewActivity(int position) {
    Intent intent = new Intent(getActivity(), ViewImageViewPagerActivity.class);
    intent.putExtra("images", galleryListInString);
    intent.putExtra("image_position", position);
    getActivity().startActivity(intent);
}

intentViewActivity方法的一个参数是ViewImageViewPagerActivity,它是:

package com.epicamera.vms.i_neighbour.activity;



  public class ViewImageViewPagerActivity extends AppCompatActivity {
  private String TAG = "ViewImageViewPagerActivity";

Toolbar toolbar;
private View temp_view;
private VideoView vv;
private TextView toolbar_title;
private ViewPager insideViewPager;
private MyViewPagerAdapter myViewPagerAdapter;
ArrayList<HashMap<String, Object>> imageList = new ArrayList<>();

Bitmap bmp = null;
ImageLoader imageLoader = ImageLoader.getInstance(); // Get singleton instance
private String username, companyname, usertype, companylogo, userid, token, userphoto, usergender;
private String android_id;
private String regId;
private Bitmap attachment = null;
private int imagePosition = 0, actualPosition = 0;
private int onPageScrollPosition = 0;
private boolean isVideo = false;

private Handler fileCheckerHandler = new Handler();
private Runnable fileCheckerRunnable = null;

private Uri uri;

// AsyncTask
AsyncTask<Void, Void, Boolean> task;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_view_image_video_viewpager);
    CommonUtilities.toggleRotationAdvance(this);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar_title = (TextView) findViewById(R.id.toolbar_title);
    setSupportActionBar(toolbar);

    getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_action_back);
    // enable ActionBar app icon to behave as action to toggle nav drawer
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
    //remove the tittle
    getSupportActionBar().setDisplayShowTitleEnabled(false);


    SessionManager session = new SessionManager(this.getApplicationContext());
    // get user data from session
    HashMap<String, String> user = session.getUserDetails();
    // session id
    username = user.get(SessionManager.KEY_USERNAME);
    // user id
    companyname = user.get(SessionManager.KEY_COMPANYNAME);
    // company id
    usertype = user.get(SessionManager.KEY_USERTYPE);
    // company id
    companylogo = user.get(SessionManager.KEY_COMPANYLOGO);
    // user id
    userid = user.get(SessionManager.KEY_USERID);
    // session token
    token = user.get(SessionManager.KEY_TOKEN);
    // session user photo
    userphoto = user.get(SessionManager.KEY_USERPHOTO);


    usergender = user.get(SessionManager.KEY_USERGENDER);

    android_id = Settings.Secure.getString(getContentResolver(),
            Settings.Secure.ANDROID_ID);

    insideViewPager = (ViewPager) findViewById(R.id.inside_view_pager);

    imageList = (ArrayList<HashMap<String,Object>>) getIntent().getExtras().getSerializable("images");
    imagePosition = getIntent().getExtras().getInt("image_position");

    actualPosition = imagePosition;


    myViewPagerAdapter = new MyViewPagerAdapter(ViewImageViewPagerActivity.this, imageList);
    insideViewPager.setAdapter(myViewPagerAdapter);
    insideViewPager.addOnPageChangeListener(viewPagerPageChangeListener);
    insideViewPager.setOffscreenPageLimit(imageList.size());
    insideViewPager.setCurrentItem(actualPosition, false);
    myViewPagerAdapter.notifyDataSetChanged();

    toolbar_title.setText(actualPosition + 1 + " / " + (imageList.size()));
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

//        return super.onCreateOptionsMenu(menu);
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.view_image_menu, menu);
    return true;
}

/* Called whenever we call invalidateOptionsMenu() */
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Log.d(TAG, "id: " + item.getItemId());
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;
        case R.id.action_savetogallery:

            String[] count = toolbar_title.getText().toString().split("/");
            int value = Integer.parseInt(count[0].trim()) - 1;
            HashMap<String, String> child = new HashMap<>();
            child.put("image", (String) imageList.get(value).get("image"));

            saveToGallery(child, "File");
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

@Override
public void onBackPressed() {
    super.onBackPressed();
}

@Override
protected void onPause() {
    super.onPause();
}

@Override
protected void onResume() {
    super.onResume();
}

public void saveToGallery(HashMap<String, String> item, final String type) {
    //take the current position
    final String select_document_link = item.get("image");
    final String select_document_name = item.get("image");
    final String selected_document = select_document_name.substring(select_document_name.lastIndexOf('/') + 1, select_document_name.length());
    final String document_download_path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM + "/i-Neighbour").getPath() + File.separator + selected_document;
    final File file = new File(document_download_path);

    Log.d(TAG, "path: " + document_download_path + " " + select_document_link);

    // Check is the file is exist
 //        if (file.exists()) {
//            //Open the file if exist
//            openFile(file);
//        } else {
    //Download and open the file, if does not exist
    try {
        Toast.makeText(ViewImageViewPagerActivity.this, "Downloading...", Toast.LENGTH_SHORT).show();
//                final ProgressDialog progDailog = ProgressDialog.show(this,
//                        this.getResources().getString(R.string.txt_title_downloading),
//                        this.getResources().getString(R.string.txt_document_downloading), true);
        new Thread() {
            public void run() {
                try {
                    //Download the document
                    final DownloadManager downloadManager;
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM + "/i-Neighbour").mkdirs();


                    downloadManager = (DownloadManager) ViewImageViewPagerActivity.this.getSystemService(Context.DOWNLOAD_SERVICE);
                    // have to replace space to %20
                    String url = select_document_link.replace(" ", "%20");
                    Uri uri = Uri.parse(url);
                    DownloadManager.Request request = new DownloadManager.Request(uri)
                            .setTitle(selected_document)
                            .setDestinationInExternalPublicDir(Environment.DIRECTORY_DCIM + "/i-Neighbour",
                                    selected_document)
                            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                    downloadManager.enqueue(request);

                    //ADDED LOOP HERE UNTIL FILE DOWNLOAD IS COMPLETE
                    fileCheckerRunnable = new Runnable() {
                        public void run() {
                            DownloadManager.Query query = new DownloadManager.Query();
                            query.setFilterByStatus(DownloadManager.STATUS_FAILED | DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_SUCCESSFUL | DownloadManager.STATUS_RUNNING | DownloadManager.STATUS_PENDING);
                            Cursor cursor = downloadManager.query(query);
                            if (cursor.moveToFirst()) {
                                int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
                                switch (status) {
                                    case DownloadManager.STATUS_PAUSED:
                                        //download is waiting to retry or resume
                                        fileCheckerHandler.postDelayed(this, 1000);
                                        break;
                                    case DownloadManager.STATUS_PENDING:
                                        //download is waiting to start
                                        fileCheckerHandler.postDelayed(this, 1000);
                                        break;
                                    case DownloadManager.STATUS_RUNNING:
                                        //download is currently running
                                        fileCheckerHandler.postDelayed(this, 1000);
                                        break;
                                    case DownloadManager.STATUS_SUCCESSFUL:
                                        //download has successfully completed
                                        //Open the document
//                                                openFile(file);
                                        Toast.makeText(ViewImageViewPagerActivity.this, type + " saved to Gallery->i-
Neighbour", Toast.LENGTH_SHORT).show();
 //                                                    progDailog.dismiss();

                                        //STOP REPEATING TASK
                                        fileCheckerHandler.removeCallbacks(fileCheckerRunnable);
                                        break;
                                    case DownloadManager.STATUS_FAILED:
                                        //download has failed (and will not be retried)
 //                                                    progDailog.dismiss();

                                        //STOP REPEATING TASK
                                        fileCheckerHandler.removeCallbacks(fileCheckerRunnable);
                                        break;
                                }
                            }
                        }
                    };
                    fileCheckerHandler.postDelayed(fileCheckerRunnable, 1000);

                } catch (Exception e) {
                    Log.d(TAG, "Error: " + e);
                }
            }
        }.start();

    } catch (Exception e) {
        Log.e("ERROR", "Error -> " + e.getMessage());
    }
}

//  outside viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {

    @Override
    public void onPageSelected(int position) {
        toolbar_title.setText(position + 1 + " / " + (imageList.size()));

        onPageScrollPosition = position;
        Log.d(TAG, "onpagescrollposition: " + onPageScrollPosition);
    }

    @Override
    public void onPageScrolled(int pos, float arg1, int arg2) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {


    }
};

/**
 * View pager adapter
 */
public class MyViewPagerAdapter extends PagerAdapter {
    private LayoutInflater layoutInflater;
    private Context context;
    private ArrayList<HashMap<String, Object>> images;

    public MyViewPagerAdapter(Context context, ArrayList<HashMap<String, Object>> images) {
        this.context = context;
        this.images = images;
        layoutInflater = LayoutInflater.from(context);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View view = layoutInflater.inflate(R.layout.view_pager_image_video2, null);
        final VideoView vvFullScreen = (VideoView) view.findViewById(R.id.vv_full_screen);
        final TouchImageView imgFullScreen = (TouchImageView) view.findViewById(R.id.img_full_screen);
        final ImageView imgVideoBg = (ImageView) view.findViewById(R.id.img_video_bg);
        final ProgressBar pBar = (ProgressBar) view.findViewById(R.id.pBar);
        final LinearLayout llVideoPlay = (LinearLayout) view.findViewById(R.id.ll_video_play);


        view.setTag("pos" + position);
        //Bitmap image = (Bitmap) images.get(position).get("image");
        String image_url = (String) images.get(position).get("image");

        imgFullScreen.setVisibility(View.VISIBLE);
        vvFullScreen.setVisibility(View.GONE);
        llVideoPlay.setVisibility(View.GONE);

        Glide.with(context).load(image_url)
                .thumbnail(0.5f)
                .crossFade()
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(imgFullScreen);

        container.addView(view);
        return view;
    }

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

    @Override
    public boolean isViewFromObject(View view, Object obj) {
        return view == obj;
    }

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

    @Override
    public int getItemPosition(Object object) {
        return super.getItemPosition(object);
    }
}
}

0 个答案:

没有答案