是否可以像使用radiobutton一样使用checked和unchecked进行Imageview?

时间:2015-04-18 09:21:22

标签: java android android-checkbox

我在Horizo​​ntalscrollview里面的Imageview中有近500张图片。如果我正在选择图像,那么我将其标记为已选中。如果我在视图中选择任何其他图像,则应取消选择,并且必须选择新单击的图像。我怎么能实现它?

for (int i = 0; i < Home.arr_category_item_list.size(); i++) {
        ImageView circleImageView = new ImageView(getActivity());
        imageLoader.get(Home.arr_category_item_list.get(i).get(Variables.EST_CATEGORY_ITEM_IMAGE), ImageLoader.getImageListener(circleImageView, R.drawable.defaultimage, R.drawable.defaultimage));
        circleImageView.setTag(Integer.parseInt(Home.arr_category_item_list.get(i).get(Variables.EST_CATEGORY_ITEM_ID)));
        circleImageView.setLayoutParams(params);
        lnr_category_item.addView(circleImageView);

    }

请检查附带的图像。在屏幕的底部有一个图像视图。因此,用户可以选择一次只选择一个图像。

enter image description here

1 个答案:

答案 0 :(得分:0)

现在这是一些非常古老的代码,希望它仍然有用。

注意:可能会遗漏一两件事,但您可以从此实施中获得想法

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;

import yourpackage.R;

//Creataed by Bojan Kseneman on 14.8.2013

public class CustomCheckBox extends ImageView {

    private boolean isChecked;
    private boolean isImageShown;
    private boolean useCustomClickListener;
    //private String android_xmlns = "http://schemas.android.com/apk/res/android";
    private String app_xmlns;
    private int checkboxOnResID;
    private int checkboxOffResID;
    private int checkboxDisabledOnResID;
    private int checkboxDisabledOffResID;

    //private int imageHeight;
    //private int imageWidth;

    public CustomCheckBox(Context context, AttributeSet attrs) {
        super(context, attrs);
        app_xmlns = new StringBuilder("http://schemas.android.com/apk/res/" + context.getPackageName()).toString();
        init(attrs);
    }

    private void init(AttributeSet attrs) {

        checkboxOnResID = attrs.getAttributeResourceValue(app_xmlns, "resourceChecked", R.drawable.round_checkbox_on);
        checkboxOffResID = attrs.getAttributeResourceValue(app_xmlns, "resourceNotChecked", R.drawable.round_checkbox_off);
        checkboxDisabledOnResID = attrs.getAttributeResourceValue(app_xmlns, "resourceDisabledOn", R.drawable.round_checkbox_off);
        checkboxDisabledOffResID = attrs.getAttributeResourceValue(app_xmlns, "resourceDisabledOff", R.drawable.round_checkbox_off);
        useCustomClickListener = attrs.getAttributeBooleanValue(app_xmlns, "customClickEvent", false);
        if (useCustomClickListener)
            this.setOnTouchListener(new CboxTouchListener());
        else {
            this.setOnTouchListener(new NormalClickListener());
        }

        if (!hasOnClickListener()) {
            /**
             * assign a new onClick listener so we get desired onClick sound
             * effect (because we call it) this is opposite to how android
             * behaves, where you don't hear the sound if there is not
             * onClickListener assigned
             */
            this.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                }
            });
        }
    }

    private boolean hasOnClickListener() {
        try {
            if (android.os.Build.VERSION.SDK_INT >= 14) {
                //the information is inside ListenerInfo
                java.lang.reflect.Field listenerInfoField = null;
                listenerInfoField = Class.forName("android.view.View").getDeclaredField("mListenerInfo");
                if (listenerInfoField != null)
                    listenerInfoField.setAccessible(true);
                Object mOnClickListener = null;
                mOnClickListener = listenerInfoField.get(this); //get from view object, in this case this is this

                // get the field mOnClickListener, that holds the listener and cast it to a listener
                java.lang.reflect.Field listenerField = null;
                listenerField = Class.forName("android.view.View$ListenerInfo").getDeclaredField("mOnClickListener");
                //View.OnClickListener myListener = (View.OnClickListener) listenerField.get(myLiObject);
                return (listenerField.get(mOnClickListener) != null);
            }
            else {
                //directly in View
                java.lang.reflect.Field f = Class.forName("android.view.View").getDeclaredField("mOnClickListener");
                return (f.get(this) != null);
            }
        }
        catch (Exception e) {
            return false;
        }
    }

    //  private void setScaledDownImage(int resID) {
    //      this.setImageBitmap(CommonMethods.decodeSampledBitmapFromResource(getContext(), resID, imageWidth, imageHeight));
    //  }

    public boolean isChecked() {
        return (isChecked && this.isEnabled());
    }

    public void setChecked(boolean isChecked) {
        if (this.isEnabled())
            setCheckedIgnoreEnabled(isChecked);
        else
            this.setEnabled(false);
    }

    public void setCheckedIgnoreEnabled(boolean isChecked) {
        if ((this.isChecked != isChecked) || !isImageShown) {
            this.isChecked = isChecked;
            if (isChecked)
                setImageResource(checkboxOnResID);
            else
                setImageResource(checkboxOffResID);
        }
    }

    @Override
    public void setEnabled(boolean enabled) {
        super.setEnabled(enabled);
        if (enabled)
            setChecked(isChecked);
        else {
            int resID = isChecked ? checkboxDisabledOnResID : checkboxDisabledOffResID;
            setImageResource(resID);
        }
    }

    public void setCheckedAndEnabled(boolean isChecked, boolean isEnabled) {
        setCheckedIgnoreEnabled(isChecked);
        setEnabled(isEnabled);
    }

    public void toggle() {
        setChecked(!isChecked);
    }

    public void toggleWithClick() {
        toggle();
        this.performClick();
    }

    public void toggleWithSilentClick() {
        //v.playSoundEffect(android.view.SoundEffectConstants.CLICK);
        boolean currentState = this.isSoundEffectsEnabled();
        this.setSoundEffectsEnabled(false);
        toggleWithClick();
        this.setSoundEffectsEnabled(currentState);
    }

    private class CboxTouchListener extends ImageBoundClickListener {
        @Override
        public void doSomething() {
            super.doSomething();
            setChecked(!isChecked);
            CustomCheckBox.this.performClick();
        }
    }

    private class NormalClickListener extends MyOnClickListener {
        @Override
        public void doSomething() {
            super.doSomething();
            setChecked(!isChecked);
            CustomCheckBox.this.performClick();
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        //this.imageWidth = MeasureSpec.getSize(widthMeasureSpec);
        //this.imageHeight = MeasureSpec.getSize(heightMeasureSpec);
        if (!isImageShown) {
            setChecked(isChecked);
            isImageShown = !isImageShown;
        }

    }

}

我使用了这个点击监听器,因为我使用了一些圆形图像,当用户点击图像的透明部分时,我不想触发点击事件。

public abstract class ImageBoundClickListener implements android.view.View.OnTouchListener {

    private String TAG = "ImageBoundsTouchListener";
    private boolean shouldTriggerAction = false;
    Rect allowedArea;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        //let's us detect only clicks on the part where actual image is and not where the ImageView is
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                float[] eventXY = new float[] { event.getX(), event.getY() };
                allowedArea = new Rect(v.getLeft(), v.getTop(), v.getRight(), v.getBottom());
                android.graphics.Matrix invertMatrix = new android.graphics.Matrix();
                ImageView iv = (ImageView) v;
                iv.getImageMatrix().invert(invertMatrix);
                invertMatrix.mapPoints(eventXY);

                int x = (int) eventXY[0];
                int y = (int) eventXY[1];

                Drawable imgDrawable = iv.getDrawable();
                Bitmap bitmap = ((BitmapDrawable) imgDrawable).getBitmap();

                //Limit x,y within the bitmap
                if (x < 0)
                    x = 0;
                else if (x > (bitmap.getWidth() - 1))
                    x = bitmap.getWidth() - 1;

                if (y < 0)
                    y = 0;
                else if (y > bitmap.getHeight() - 1)
                    y = bitmap.getHeight() - 1;

                int touchedRGB = bitmap.getPixel(x, y);
                //is transparent?
                shouldTriggerAction = (touchedRGB == 0) ? false : true;
                return true;
            case MotionEvent.ACTION_MOVE:
                if (!allowedArea.contains(v.getLeft() + (int) event.getX(), v.getTop() + (int) event.getY()))
                    //the user went out of the user area
                    shouldTriggerAction = false;
                return true;
            case MotionEvent.ACTION_UP:
                //finger is no longer on screen
                if (shouldTriggerAction)
                    doSomething();
                return true;
            default:
                return false;
        }
    }

    public void doSomething() {

    }

}