-1

我已经按照本教程实施了一个自定义画廊:http: //vikaskanani.wordpress.com/2011/07/20/android-custom-image-gallery-with-checkbox-in-grid-to-select-multiple/。它工作正常,但我想对其进行一些修改。例如,当我单击一个复选框时,它会被选中并选择图像。但是,如果单击图像,它不会被选中,并且复选框不会被选中。你能帮我理解我该如何修改它吗?这是我正在尝试使用的代码:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.custom_gallery); //assign the layout file to the activity

    final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
    final String orderBy = MediaStore.Images.Media._ID;
    Cursor imagecursor = managedQuery( //create the cursor for navigate inside the database device and retrieve informations about the media contents like photo, video ecc...
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
            null, orderBy);
    int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID); //get the current column index
    this.count = imagecursor.getCount(); //count the external content uri of the cursor
    this.thumbnails = new Bitmap[this.count]; //create an array of bitmap using the size retrieved from the count variable
    this.arrPath = new String[this.count]; //create the array that contains the list of the path of the media (photos in this case)
    this.thumbnailsselection = new boolean[this.count]; //initialize the array of boolean to save informations about the selection of the thumbnails
    for (int i = 0; i < this.count; i++) {
        imagecursor.moveToPosition(i); //let's start from the first position and move one by one until the end
        int id = imagecursor.getInt(image_column_index);
        int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
        thumbnails[i] = MediaStore.Images.Thumbnails.getThumbnail( //take the thumbnails of the images and store it inside the array using the MICRO format for avoid high memory usage
                getApplicationContext().getContentResolver(), id,
                MediaStore.Images.Thumbnails.MICRO_KIND, null);
        arrPath[i]= imagecursor.getString(dataColumnIndex);
    }
    GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid); //assign the GridView to the equivalent element in the xml file
    imageAdapter = new ImageAdapter(); //create a new imageAdapter. It is used how source for all the items in the gridView
    imagegrid.setAdapter(imageAdapter);
    imagecursor.close(); //close the image cursor when we arrive to the end of the columns to analize

    final Button selectBtn = (Button) findViewById(R.id.selectBtn); //assign the button to the equivalent in the xml layout
    selectBtn.setOnClickListener(new OnClickListener() { //create a listener for reveal when it is pressed

        public void onClick(View v) {
            // TODO Auto-generated method stub
            final int len = thumbnailsselection.length;
            int cnt = 0; //initialize a count for check the number of selected photos
            String selectImages = "";
            for (int i =0; i<len; i++)
            {
                if (thumbnailsselection[i]){
                    cnt++;
                    selectImages = selectImages + arrPath[i] + "|"; //store the correct path of the images in the variable (we can use this string for find the images path in others activity)         
                }
            }
            //if no one image is selected show a message to the user
            if (cnt == 0){
                Toast.makeText(getApplicationContext(),
                        "Please select at least one image",
                        Toast.LENGTH_LONG).show();
            } else {
                //If at least one image is selected we create a new activity where the images are displayed and the user can manage them
                Intent photoManagementIntent = new Intent(
                        getApplicationContext(),
                        PhotoManagement.class //select the class for the next activity
                        );
                photoManagementIntent.putExtra("Selected Images",""+selectImages); //add an extra parameter that contains the path of the selected images. In this mode we can read it in the next activity
                startActivity(photoManagementIntent); //start the new activity
            }
        }
    });
}

public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mInflater.inflate(
                    R.layout.gallery_item, 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();
        }
        holder.checkbox.setId(position);
        holder.imageview.setId(position);
        holder.checkbox.setOnClickListener(new OnClickListener() { //create a listener for the checkbox for check or uncheck it
            public void onClick(View v) {
                // TODO Auto-generated method stub
                CheckBox cb = (CheckBox) v;
                int id = cb.getId();
                if (thumbnailsselection[id]){
                    cb.setChecked(false); //uncheck the checkbox
                    thumbnailsselection[id] = false;
                } else {
                    cb.setChecked(true); //check the checkbox
                    thumbnailsselection[id] = true;
                }
            }
        });
        holder.imageview.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Log.i("IMAGE","PRESSED");
                ImageView iv = (ImageView) v;
                CheckBox cb = (CheckBox) v;
                int id = iv.getId();
                cb.setChecked(thumbnailsselection[id]);

            }
        });
        holder.imageview.setImageBitmap(thumbnails[position]); //set the image in the correct position in the view
        holder.checkbox.setChecked(thumbnailsselection[position]); //set the checkbox in the correct position
        holder.id = position;
        return convertView;
    }
}

这是使用我的代码发生的错误:

09-27 15:30:48.895: E/AndroidRuntime(4526): FATAL EXCEPTION: main
09-27 15:30:48.895: E/AndroidRuntime(4526): java.lang.ClassCastException: android.widget.ImageView cannot be cast to android.widget.CheckBox
09-27 15:30:48.895: E/AndroidRuntime(4526):     at com.example.dilandprints2.CustomGallery$ImageAdapter$2.onClick(CustomGallery.java:146)
09-27 15:30:48.895: E/AndroidRuntime(4526):     at android.view.View.performClick(View.java:4204)
09-27 15:30:48.895: E/AndroidRuntime(4526):     at android.view.View$PerformClick.run(View.java:17355)
09-27 15:30:48.895: E/AndroidRuntime(4526):     at android.os.Handler.handleCallback(Handler.java:725)
09-27 15:30:48.895: E/AndroidRuntime(4526):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-27 15:30:48.895: E/AndroidRuntime(4526):     at android.os.Looper.loop(Looper.java:137)
09-27 15:30:48.895: E/AndroidRuntime(4526):     at android.app.ActivityThread.main(ActivityThread.java:5041)
09-27 15:30:48.895: E/AndroidRuntime(4526):     at java.lang.reflect.Method.invokeNative(Native Method)
09-27 15:30:48.895: E/AndroidRuntime(4526):     at java.lang.reflect.Method.invoke(Method.java:511)
09-27 15:30:48.895: E/AndroidRuntime(4526):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
09-27 15:30:48.895: E/AndroidRuntime(4526):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
09-27 15:30:48.895: E/AndroidRuntime(4526):     at dalvik.system.NativeStart.main(Native Method)
09-27 15:30:51.446: E/Trace(4545): error opening trace file: No such file or directory (2)

谢谢

4

2 回答 2

1

您应该查看本教程:Android Checkbox Example - Mkyong.com。它向您展示了如何为您的复选框实现 onClick 侦听器。以下是链接中侦听器的实际代码:

chkIos.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View v) {
                //is chkIos checked?
        if (((CheckBox) v).isChecked()) {
            Toast.makeText(MyAndroidAppActivity.this,
               "Bro, try Android :)", Toast.LENGTH_LONG).show();
        }

      }
    });
于 2013-09-27T15:44:20.987 回答
1

问题在于:

ImageView iv = (ImageView) v;
CheckBox cb = (CheckBox) v;

视图如何既是 ImageView 又是 CheckBox?第二行将 ImageView 转换为 CheckBox,从而将其java.lang.ClassCastException放入您的 logcat 中。

您需要获取与您的 ImageView 关联的 CheckBox 的引用。

一种可能的方法是像这样使用视图的父级:

LinearLayout row = (LinearLayout) v.getParent();
CheckBox cb = (CheckBox) row.findViewById(R.id.itemCheckBox);
于 2013-09-27T15:44:52.063 回答