android - ArrayAdapter<> 在 onPause() 中不清除,android

标签 android android-fragments android-arrayadapter android-gridview android-sdcard

我一直在研究这个,但一无所获。我的ArrayAdapter<>对于我的 GridViewFragment标签。我得出的结论是,因为它在一个 fragment 中,所以当我浏览选项卡然后返回到我的照片选项卡时,它不会从头开始重新上传图像,而是上传图像并将相同的图像添加到适配器。这会产生 2 组相同的图像,但我只需要一组在重新访问该选项卡时上传。

我试着把 adapter.clear()其次是 adapter.notifyDataSetChanged()进入我的onPause() fragment 生命周期方法。因此,当 fragment 不再可见时,所有适配器项都会清除,当 fragment 再次可见时,它会从我的 SD 卡加载图像的新副本。但这是行不通的,除了先前加载的图像集之外,它仍然添加了新的图像集。任何人都知道如何清除适配器,这样我就不会在每次重新访问选项卡时都添加相同的图像?或者如果有另一种我不知道的方法...提前致谢。

更新:

感谢大家的贡献,我终于找到了一个有用的解决方法。我记录了我所有的 adapter不同阶段的变量,发现无论我在哪里清除它,它总是会在 loadSDCard() 中发布一个重复集。方法,所以它一定是从那里来的。所以我只是在我的适配器上设置了一个条件,以防止它再次加载。我注意到我的适配器在从其他选项卡返回后已经加载,使用 getCount()在上面。这来 self 的 PhotoTab.java并且是缺失的部分:

if (adapter.getCount() == 0) {
            adapter.addAll(loadSDCard());

            // add the default icons remaining, to GridView, if less than 24 files on SD card
            for (int i = 0; i < (24 - photoList.size()); i++) {

                adapter.add(new PhotoGridItem(BitmapFactory.decodeResource(getResources(),
                        R.drawable.ic_photo_placeholder)));
            }

        }

更新 2:

请参阅下面的回答,我首先找到了重复发生的真正原因。

enter image description here

PhotoTab.java

package org.azurespot.cutecollection;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;

import org.azurespot.R;

import java.io.File;
import java.util.ArrayList;

/**
 * Created by mizu on 2/8/15.
 */
public class PhotoTab extends Fragment {

    private GridView gridView;
    File[] files;
    ArrayList<PhotoGridItem> photoList = new ArrayList<>();
    ArrayAdapter<PhotoGridItem> adapter;
    Bitmap bitmap;

    public PhotoTab() {
        super();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.photo_tab, container, false);

        // with fragments, make sure you include the rootView when finding id
        gridView = (GridView) v.findViewById(R.id.photo_grid);
        adapter = new GridViewPhotoAdapter(getActivity(), R.layout.photo_grid_item);
        // Set the Adapter to GridView
        gridView.setAdapter(adapter);
        adapter.addAll(loadSDCard());

        // add the default icons remaining, to GridView, if less than 24 files on SD card
        for (int i = 0; i < (24 - photoList.size()); i++) {

            adapter.add(new PhotoGridItem(BitmapFactory.decodeResource(getResources(),
                    R.drawable.ic_photo_placeholder)));
        }

        return v;
    }


    private ArrayList<PhotoGridItem> loadSDCard() {

        try {
            // gets directory CutePhotos from sd card
            File cutePhotosDir = new File(Environment.getExternalStoragePublicDirectory
                    (Environment.DIRECTORY_PICTURES), "CutePhotos");
            // lists all files in CutePhotos, loads in Files[] array
            files = cutePhotosDir.listFiles();

            for (File singleFile : files) {
                String filePath = singleFile.getAbsolutePath();

                // this method makes size small for the view (to save memory)
                bitmap = decodeSampledBitmap(filePath, 270, 270);

                photoList.add(new PhotoGridItem(bitmap));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return photoList;
    }

    public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

    public static Bitmap decodeSampledBitmap(String path, int reqWidth, int reqHeight) {

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(path, options);
    }

    @Override
    public void onPause(){
        super.onPause();
        adapter.clear();
        adapter.notifyDataSetChanged();

    }

}

GridViewPhotoAdapter

    package org.azurespot.cutecollection;

/**
* Created by mizu on 2/5/15.
*/
// package org.azurespot.cutecollection;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;

import org.azurespot.R;

/**
 * Created by mizu on 2/5/15.
 */
public class GridViewPhotoAdapter extends ArrayAdapter<PhotoGridItem> {

    public Context context;
    private int resourceId;
    Bitmap bm;

    public GridViewPhotoAdapter(Context context, int layoutResourceId) {
        super(context, layoutResourceId);
        this.context = context;
        this.resourceId = layoutResourceId;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View row = convertView;
        final ViewHolder holder;

        if (row == null) {

            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(resourceId, parent, false);

            holder = new ViewHolder();
            holder.imageView = (ImageView) row.findViewById(R.id.photo_grid_view);
            // stores holder with view
            row.setTag(holder);

        } else {

            holder = (ViewHolder)row.getTag();
        }

        PhotoGridItem photoGridItem = getItem(position);

        if (photoGridItem != null) {
            bm = photoGridItem.getImage();
            holder.imageView.setImageBitmap(bm);

            // positioning the image in the GridView slot
            holder.imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            holder.imageView.setLayoutParams(new LinearLayout.LayoutParams(270, 270));
        }

        return row;

    }

    public class ViewHolder{
        ImageView imageView;
    }

}

PhotoGridItem

package org.azurespot.cutecollection;

import android.graphics.Bitmap;

/**
 * Created by mizu on 3/19/15.
 */
public class PhotoGridItem {

    private Bitmap image;

    public PhotoGridItem(Bitmap image) {
        super();
        this.image = image;
    }

    public Bitmap getImage() {
        return image;
    }

    public void setImage(Bitmap image) {
        this.image = image;
    }

}

最佳答案

Fragment.onPause() 与 fragment 的可见性无关。 Fragment.onPause() 与其封装的 Activity.onPause() 相关联。即 Fragment.onPause() 只会在 Activity.onPause() 被调用后被调用。

如果您想在 Fragment 变得可见时更新它,我建议您使用 Fragment.setUserVisibleHint() 或使用 ViewPager.onPageChangeListener() 让您知道您的 Fragment 何时被选中并相应地更新其内容。

关于android - ArrayAdapter<> 在 onPause() 中不清除,android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29220290/

相关文章:

android - 页面加载后如何触发对 WebView 中文本输入字段的关注?

android - 即使在设置 launchMode ="singleTop"后也会重新创建 Activity

android - 从 ArrayAdapter 内启动 Activity

android - (ActionBar) Tabs + Pager + detail Fragments inside ViewPager 容器

android - java.lang.IllegalStateException : Fragment no longer exists for key f1: index 3

Android AsyncTask SoapObject 请求问题

android - 更新有关自动完成 TextView 项目单击的建议

android - 如何等待用户启用移动数据并发送邮件?

java - Android:如何为 Activity.onNewIntent() 设置监听器?

java - 调试在启动时运行的应用程序