如何在Fragment中使用标签主机和滑动菜单在网格视图中设置图像适配器?

时间:2015-04-15 06:04:07

标签: android android-fragments baseadapter

我通过应用程序相机按钮捕获图像,从特定文件夹中的片段中设置图像适配器。但是在捕获图像后它不会刷新图像适配器。

这是我的代码:

public class FragmentTab1 extends Fragment {

public ImageAdapter imageAdapter;
private final static int TAKE_IMAGE = 1;
private final static int UPLOAD_IMAGES = 2;
private final static int VIEW_IMAGE = 3;
private Uri imageUri;
private MediaScannerConnection mScanner;
public GridView imagegrid;
private long lastId;
android.hardware.Camera.Parameters parameters;
android.hardware.Camera.Size size;
public Context ctx;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragmenttab1, container, false);

    ctx=getActivity();
    imageAdapter = new ImageAdapter(ctx);
    imageAdapter.initialize();
    imagegrid = (GridView) rootView.findViewById(R.id.PhoneImageGrid);

    final Button PhotoBtn = (Button) rootView.findViewById(R.id.PhotoBtn);
    PhotoBtn.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
            String fileName = "IMG_" + sdf.format(new Date()) + ".jpg";
            File myDirectory = new File(Environment
                    .getExternalStorageDirectory() + "/PHOTOAPP/");
            myDirectory.mkdirs();
            File file = new File(myDirectory, fileName);
            imageUri = Uri.fromFile(file);
            Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            //parameters=Camera.
            //intent.putExtra(MediaStore.EXTRA_SIZE_LIMIT,153600L);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            startActivityForResult(intent, TAKE_IMAGE);
        }
    });

    imagegrid.setAdapter(imageAdapter);
    return rootView;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
        case TAKE_IMAGE:
            try {
                if (resultCode ==Activity. RESULT_OK) {

                    // we need to update the gallery by starting MediaSanner service.
                    mScanner = new MediaScannerConnection(
                            getActivity(),
                            new MediaScannerConnection.MediaScannerConnectionClient() {
                                public void onMediaScannerConnected() {
                                    mScanner.scanFile(imageUri.getPath(), null /* mimeType */);
                                }

                                public void onScanCompleted(String path, Uri uri) {

                                    if (path.equals(imageUri.getPath())) {
                                        mScanner.disconnect();
                                        //we need to create new UI thread because, we can't update our mail thread from here
                                        //Both the thread will run one by one, see documentation of android  
                                        getActivity()
                                                .runOnUiThread(new Runnable() {
                                                    public void run() {
                                                        updateUI();
                                                    }
                                                });
                                    }
                                }
                            });
                    mScanner.connect();

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            break;
        case UPLOAD_IMAGES:
            if (resultCode == Activity.RESULT_OK){
                //do some code where you integrate this project
            }
            break;
        }
    }

    public void updateUI() {
        ctx=getActivity().getParent();
        imageAdapter = new ImageAdapter(ctx);
        //imageAdapter.initialize();
        imageAdapter.checkForNewImages();

    }


 public class ImageAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        public ArrayList<ImageItem> images = new ArrayList<ImageItem>();

        public ImageAdapter(Context c) {
            ctx=c;
            mInflater = (LayoutInflater)getActivity(). getSystemService(getActivity().LAYOUT_INFLATER_SERVICE);
        }

        @SuppressWarnings("deprecation")
        public void initialize() {
            images.clear();
            final String[] columns = { MediaStore.Images.Thumbnails._ID };
            final String orderBy = MediaStore.Images.Media._ID;
         ContentResolver Resolver = getActivity().getContentResolver();
            Cursor imagecursor = Resolver.query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    columns,MediaStore.Images.Media.DATA + " like ? ",
                    new String[] {"%PHOTOAPP%"},orderBy);
            if(imagecursor != null){
                int image_column_index = imagecursor
                        .getColumnIndex(MediaStore.Images.Media._ID);
                int count = imagecursor.getCount();
                for (int i = 0; i < count; i++) {
                    imagecursor.moveToPosition(i);
                    int id = imagecursor.getInt(image_column_index);
                    ImageItem imageItem = new ImageItem();
                    imageItem.id = id;
                    lastId = id;
                    imageItem.img = MediaStore.Images.Thumbnails.getThumbnail(
                            getActivity().getContentResolver(), id,
                            MediaStore.Images.Thumbnails.MINI_KIND, null);
                    images.add(imageItem);
                }
                //imagecursor.close();
            }
            notifyDataSetChanged();
        }

        @SuppressWarnings("deprecation")
        public void checkForNewImages(){
            //Here we'll only check for newer images
            final String[] columns = { MediaStore.Images.Thumbnails._ID };
            final String orderBy = MediaStore.Images.Media._ID;
            Cursor imagecursor=null;
            ContentResolver Resolver = getActivity().getContentResolver();
            System.out.println("SIZE="+images.size());
            if(images.size()==0){

                imagecursor = Resolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        columns,MediaStore.Images.Media.DATA + " like ? ",
                        new String[] {"%PHOTOAPP%"},orderBy);
            }

            else{
                imagecursor = Resolver.query(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
                        MediaStore.Images.Media._ID + " > " + lastId , null, orderBy);
            }

            int image_column_index = imagecursor
                    .getColumnIndex(MediaStore.Images.Media._ID);
            int count = imagecursor.getCount();
            for (int i = 0; i < count; i++) {
                imagecursor.moveToPosition(i);
                int id = imagecursor.getInt(image_column_index);
                ImageItem imageItem = new ImageItem();
                imageItem.id = id;
                lastId = id;
                imageItem.img = MediaStore.Images.Thumbnails.getThumbnail(
                        getActivity().getContentResolver(), id,
                        MediaStore.Images.Thumbnails.MINI_KIND, null);
                imageItem.selection = true; //newly added item will be selected by default
                images.add(imageItem);
            }
            //imagecursor.close();
            notifyDataSetChanged();
        }


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

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = mInflater.inflate(R.layout.galleryitem, null);
                holder.imageview = (ImageView) convertView
                        .findViewById(R.id.thumbImage);
                holder.checkbox = (CheckBox) convertView
                        .findViewById(R.id.itemCheckBox);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            ImageItem item = images.get(position);
            holder.checkbox.setId(position);
            holder.imageview.setId(position);
            holder.checkbox.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    CheckBox cb = (CheckBox) v;
                    int id = cb.getId();
                    if (images.get(id).selection) {
                        cb.setChecked(false);
                        images.get(id).selection = false;
                    } else {
                        cb.setChecked(true);
                        images.get(id).selection = true;
                    }
                }
            });

            holder.imageview.setImageBitmap(item.img);
            holder.checkbox.setChecked(item.selection);
            holder.checkbox.setVisibility(View.GONE);
            return convertView;
        }
 }
 class ViewHolder {
        ImageView imageview;
        CheckBox checkbox;
    }

    class ImageItem {
        boolean selection;
        int id;
        Bitmap img;
    }

}

1 个答案:

答案 0 :(得分:0)

问题出在这里,

public void updateUI() {
        ctx=getActivity().getParent();
        imageAdapter = new ImageAdapter(ctx);
        //imageAdapter.initialize();
        imageAdapter.checkForNewImages();

    }

您无需为ImageAdapter创建新实例。所以你的updateUI()就像这样,

public void updateUI() {

            imageAdapter.checkForNewImages();

        }

但是你仍然会在网格中重复最后捕获的图​​像。

为避免这种情况,您需要先清除ArrayList,然后再添加新项目。

您可以简单地使用initialize()方法或

images.clear()方法中执行checkForNewImages()

如果您在此处使用checkForNewImages()方法,则无需notifyDataSetchanged()方法调用initialize()

无论如何最终要求将变得相同,您需要在添加最后捕获的项目之前清除列表。因此,在我看来,您根本不需要checkFornewImages()方法,您可以使用initialize()方法进行notifyDataSetChanged()调用。

最后我的解决方法是,移除您的checkForNewImages()方法并修改您的updateUI()方法,如下所示,

public void updateUI() {

        imageAdapter.initialize();


    }

注意:删除checkForNewImages()无法解决您的问题。这只是拥有 DRY 代码。