Android Custom ImageView onclick监听器无法正常工作

时间:2014-08-26 10:28:27

标签: android

在我的应用程序Viewpager中,我使用名为ZoomImageView的Custom ImageView,并且它在OnClick监听器中没有触发,当我使用普通的imageview它触发时,我不知道如何在ZoomImageView中做到这一点,一些帮助真的很感激..

我的ViewPager:

class ImageGalleryViewPagerAdapter extends FragmentStatePagerAdapter {
    List<Gallery> url;
    @SuppressWarnings("deprecation")
    android.widget.Gallery gallery;

    @SuppressWarnings("deprecation")
    public ImageGalleryViewPagerAdapter(FragmentManager fm,
            List<Gallery> currentUrl, android.widget.Gallery galleryView) {
        super(fm);
        this.url = currentUrl;
        this.gallery = galleryView;
    }

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

    @Override
    public Fragment getItem(int index) {
        gallery.setSelection(index);
        ImageGalleryZoomImageFragment fragment = new ImageGalleryZoomImageFragment();
        Bundle bundle = new Bundle();
        bundle.putString(ListViewConstants.GALLERY_IMAGE_URL, url.get(index)
                .getImageUrl());
        fragment.setArguments(bundle);
        return fragment;
    }

}

我的片段:

public class ImageGalleryZoomImageFragment extends BaseFragment {
    public ZoomImageView imageView;
    private String url;
    private ImageLoader imageLoader;

    @Override
    protected void initViews() {
        url = getArguments().getString(ListViewConstants.GALLERY_IMAGE_URL);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.new_gallery_fullview, null);
        initViews();
        TrackerDetails.tracKPage(getActivity());
        imageView = (ZoomImageView) view.findViewById(R.id.selected_imageview);
        imageLoader = new ImageLoader(getActivity());
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        imageLoader.setRequiredSize(200);
        imageLoader.displayImage(url, imageView);
        imageView.setOnClickListener(new YourOnClickListener());

    }

    class YourOnClickListener implements View.OnClickListener {

    @Override
    public void onClick(View v) {
        if (getActivity().findViewById(R.id.jumeirah_gallery) != null) {
            if (getActivity().findViewById(R.id.jumeirah_gallery)
                    .getVisibility() == View.VISIBLE) {
                getActivity().findViewById(R.id.jumeirah_gallery)
                        .setVisibility(View.GONE);
            } else {
                getActivity().findViewById(R.id.jumeirah_gallery)
                        .setVisibility(View.VISIBLE);
            }
        }
    }

}
}

fragment.xml之

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/zoom_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <com.commonui.components.ZoomImageView
        android:id="@+id/selected_imageview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

1 个答案:

答案 0 :(得分:-1)

这是我实施的一个例子。 其中galleryview不存在,但它具有相同的分页,并且还点击图像正在工作。随着图像的缩放也是有效的。你只需要整合你的galleryView。

TouchImageView.class

import android.content.Context;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.ImageView;



public class TouchImageView extends ImageView {

Matrix matrix;

// We can be in one of these 3 states
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;

// Remember some things for zooming
PointF last = new PointF();
PointF start = new PointF();
float minScale = 1f;
float maxScale = 3f;
float[] m;

int viewWidth, viewHeight;
static final int CLICK = 3;
float saveScale = 1f;
protected float origWidth, origHeight;
int oldMeasuredWidth, oldMeasuredHeight;

ScaleGestureDetector mScaleDetector;

Context context;

public TouchImageView(Context context) {
    super(context);
    sharedConstructing(context);
}

public TouchImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    sharedConstructing(context);
}

private void sharedConstructing(Context context) {
    super.setClickable(true);
    this.context = context;
    mScaleDetector = new ScaleGestureDetector(context, new ScaleListener());
    matrix = new Matrix();
    m = new float[9];
    setImageMatrix(matrix);
    setScaleType(ScaleType.MATRIX);

    setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            mScaleDetector.onTouchEvent(event);
            PointF curr = new PointF(event.getX(), event.getY());

            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                last.set(curr);
                start.set(last);
                mode = DRAG;
                break;

            case MotionEvent.ACTION_MOVE:
                if (mode == DRAG) {
                    float deltaX = curr.x - last.x;
                    float deltaY = curr.y - last.y;
                    float fixTransX = getFixDragTrans(deltaX, viewWidth,
                            origWidth * saveScale);
                    float fixTransY = getFixDragTrans(deltaY, viewHeight,
                            origHeight * saveScale);
                    matrix.postTranslate(fixTransX, fixTransY);
                    fixTrans();
                    last.set(curr.x, curr.y);
                }
                break;

            case MotionEvent.ACTION_UP:
                mode = NONE;
                int xDiff = (int) Math.abs(curr.x - start.x);
                int yDiff = (int) Math.abs(curr.y - start.y);
                if (xDiff < CLICK && yDiff < CLICK)
                    performClick();
                break;

            case MotionEvent.ACTION_POINTER_UP:
                mode = NONE;
                break;
            }

            setImageMatrix(matrix);
            invalidate();
            return true; // indicate event was handled
        }

    });
}

public void setMaxZoom(float x) {
    maxScale = x;
}

private class ScaleListener extends
        ScaleGestureDetector.SimpleOnScaleGestureListener {
    @Override
    public boolean onScaleBegin(ScaleGestureDetector detector) {
        mode = ZOOM;
        return true;
    }

    @Override
    public boolean onScale(ScaleGestureDetector detector) {
        float mScaleFactor = detector.getScaleFactor();
        float origScale = saveScale;
        saveScale *= mScaleFactor;
        if (saveScale > maxScale) {
            saveScale = maxScale;
            mScaleFactor = maxScale / origScale;
        } else if (saveScale < minScale) {
            saveScale = minScale;
            mScaleFactor = minScale / origScale;
        }

        if (origWidth * saveScale <= viewWidth
                || origHeight * saveScale <= viewHeight)
            matrix.postScale(mScaleFactor, mScaleFactor, viewWidth / 2,
                    viewHeight / 2);
        else
            matrix.postScale(mScaleFactor, mScaleFactor,
                    detector.getFocusX(), detector.getFocusY());

        fixTrans();
        return true;
    }
}

void fixTrans() {
    matrix.getValues(m);
    float transX = m[Matrix.MTRANS_X];
    float transY = m[Matrix.MTRANS_Y];

    float fixTransX = getFixTrans(transX, viewWidth, origWidth * saveScale);
    float fixTransY = getFixTrans(transY, viewHeight, origHeight
            * saveScale);

    if (fixTransX != 0 || fixTransY != 0)
        matrix.postTranslate(fixTransX, fixTransY);
}

float getFixTrans(float trans, float viewSize, float contentSize) {
    float minTrans, maxTrans;

    if (contentSize <= viewSize) {
        minTrans = 0;
        maxTrans = viewSize - contentSize;
    } else {
        minTrans = viewSize - contentSize;
        maxTrans = 0;
    }

    if (trans < minTrans)
        return -trans + minTrans;
    if (trans > maxTrans)
        return -trans + maxTrans;
    return 0;
}

float getFixDragTrans(float delta, float viewSize, float contentSize) {
    if (contentSize <= viewSize) {
        return 0;
    }
    return delta;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    viewWidth = MeasureSpec.getSize(widthMeasureSpec);
    viewHeight = MeasureSpec.getSize(heightMeasureSpec);

    //
    // Rescales image on rotation
    //
    if (oldMeasuredHeight == viewWidth && oldMeasuredHeight == viewHeight
            || viewWidth == 0 || viewHeight == 0)
        return;
    oldMeasuredHeight = viewHeight;
    oldMeasuredWidth = viewWidth;

    if (saveScale == 1) {
        // Fit to screen.
        float scale;

        Drawable drawable = getDrawable();
        if (drawable == null || drawable.getIntrinsicWidth() == 0
                || drawable.getIntrinsicHeight() == 0)
            return;
        int bmWidth = drawable.getIntrinsicWidth();
        int bmHeight = drawable.getIntrinsicHeight();

        Debugger.debugE("bmSize" + "bmWidth: " + bmWidth + " bmHeight : "
                + bmHeight);

        float scaleX = (float) viewWidth / (float) bmWidth;
        float scaleY = (float) viewHeight / (float) bmHeight;
        scale = Math.min(scaleX, scaleY);
        matrix.setScale(scale, scale);

        // Center the image
        float redundantYSpace = (float) viewHeight
                - (scale * (float) bmHeight);
        float redundantXSpace = (float) viewWidth
                - (scale * (float) bmWidth);
        redundantYSpace /= (float) 2;
        redundantXSpace /= (float) 2;

        matrix.postTranslate(redundantXSpace, redundantYSpace);

        origWidth = viewWidth - 2 * redundantXSpace;
        origHeight = viewHeight - 2 * redundantYSpace;
        setImageMatrix(matrix);
    }
    fixTrans();
}
}

GalleryImageSliderActivity.class

 import java.util.ArrayList;

 import android.content.pm.ActivityInfo;
 import android.graphics.Color;
 import android.graphics.drawable.ColorDrawable;
 import android.os.Bundle;
 import android.support.v4.view.ViewPager;
 import android.support.v4.view.ViewPager.OnPageChangeListener;
 import android.support.v7.app.ActionBarActivity;
 import android.view.MenuItem;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.TextView;
 import android.widget.Toast;



 public class GalleryImageSliderActivity extends ActionBarActivity {

ViewPager myPager;
FullScreenImageAdapter adapter;
int currentSelectedImagePosition = 0;
ArrayList<String> allImages = new ArrayList<String>();
ArrayList<String> placeholder = new ArrayList<String>();
TextView txt_title;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    // this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_gallery_layout);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    txt_title = (TextView) findViewById(R.id.txt_Title);
    txt_title
            .setTypeface(CommonFunctios.getSourceSansPro(getBaseContext()));
    txt_title.setText("Photo Gallery");
    getSupportActionBar().setTitle(txt_title.getText().toString());
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setBackgroundDrawable(
            new ColorDrawable(Color.parseColor("#a40404")));
    myPager = (ViewPager) findViewById(R.id.mygalleryViewPager);
    myPager.setOnPageChangeListener(new OnPageChangeListener() {
        @Override
        public void onPageSelected(int arg0) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
            // TODO Auto-generated method stub
        }
    });
    if (getIntent().getExtras() != null) {
        if (getIntent().getExtras().containsKey("current_image_position")) {
            currentSelectedImagePosition = getIntent().getExtras().getInt(
                    "current_image_position");

        }
        if (getIntent().getExtras().containsKey("imagesList")) {
            allImages = (ArrayList<String>) (getIntent().getExtras()
                    .getStringArrayList("imagesList"));
        }
        if (getIntent().getExtras().containsKey("placeholderList")) {
            placeholder = (ArrayList<String>) (getIntent().getExtras()
                    .getStringArrayList("placeholderList"));
        }
    }
    adapter = new FullScreenImageAdapter(this, allImages, placeholder);
    myPager.setAdapter(adapter);
    myPager.setCurrentItem(currentSelectedImagePosition);
    myPager.setOffscreenPageLimit(allImages.size() * 2);
    myPager.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), "On my pager clicked",
                    Toast.LENGTH_LONG).show();
        }
    });
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
    if (item.getItemId() == android.R.id.home) {

        finish();
        overridePendingTransition(R.anim.push_right_in,
                R.anim.push_right_out);
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();
    overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
 }
 }

然后适用于图像

FullScreenImageAdapter.class

import java.util.ArrayList;

 import android.app.Activity;
 import android.content.Context;
 import android.graphics.drawable.Drawable;
 import android.support.v4.view.PagerAdapter;
 import android.support.v4.view.ViewPager;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.view.ViewGroup;
 import android.widget.ProgressBar;
 import android.widget.RelativeLayout;
 import android.widget.Toast;



 public class FullScreenImageAdapter extends PagerAdapter {

private Activity _activity;

private LayoutInflater inflater;
ArrayList<Drawable> featuredImages = new ArrayList<Drawable>();
ArrayList<String> featuredImagePath = new ArrayList<String>();
ArrayList<String> placeholdeImagepath = new ArrayList<String>();
OnClickListener onImageClickListener;
ImageLoader imgLoader;

// constructor
public FullScreenImageAdapter(Activity activity,
        ArrayList<String> featuredImagePath, ArrayList<String> placeholder) {
    this._activity = activity;
    this.featuredImagePath = featuredImagePath;
    this.placeholdeImagepath = placeholder;
    imgLoader = new ImageLoader(activity);
}

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

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

@Override
public Object instantiateItem(ViewGroup container, int position) {
    TouchImageView imgDisplay;
    inflater = (LayoutInflater) _activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View viewLayout = inflater.inflate(R.layout.full_screen_image,
            container, false);
    imgDisplay = (TouchImageView) viewLayout.findViewById(R.id.imgDisplay);
    Debugger.debugE("link url to be called "
            + placeholdeImagepath.get(position));
    imgLoader.DisplayImageWithDefaultPlaceHolder(
            featuredImagePath.get(position),
            placeholdeImagepath.get(position), imgDisplay, null,
            imgDisplay.getHeight(), imgDisplay.getWidth(), 0);
    imgDisplay.setTag(position);
    imgDisplay.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Toast.makeText(_activity, "on click", Toast.LENGTH_SHORT)
                    .show();
        }
    });
    ((ViewPager) container).addView(viewLayout);

    return viewLayout;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    ((ViewPager) container).removeView((RelativeLayout) object);

}
 }

imageview的xml文件

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<com.xxxx.TouchImageView
    android:id="@+id/imgDisplay"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scaleType="fitCenter"
    android:src="@drawable/no_data" />

</RelativeLayout>

图库活动xml。          

<TextView
    android:id="@+id/txt_Title"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:background="@color/Red_bg"
    android:gravity="center"
    android:padding="5dp"
    android:textColor="@android:color/white"
    android:textSize="@dimen/restaurant_title_size"
    android:visibility="gone" />

<android.support.v4.view.ViewPager
    android:id="@+id/mygalleryViewPager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/txt_Title"
    android:layout_centerInParent="true" />

</RelativeLayout>

首先只使用缩放类更改TouchImageView类。如果它适用于点击,则无需进行完整的解决方案。

我希望这会对你有所帮助。 Bskania。