怎么可以制作一个可点击的可绘制的?

时间:2014-08-23 22:47:39

标签: android

我是开发Android应用程序的新手,有人能告诉我如何将onClick监听器添加到可绘制的图像中?这是用于将可绘制图像置于交换模式的代码,但我希望用户能够通过单击每个可绘制图像转到另一个页面。如何将onClick方法添加到我的代码中?

public class ViewAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
        R.drawable.image_1,
        R.drawable.image_2,
        R.drawable.image_3,
        R.drawable.image_4
};
ViewAdapter(Context context){
    this.context=context;
}
@Override
public int getCount() {
    return GalImages.length;
}

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

@Override
public Object instantiateItem(ViewGroup container, int position) {
    ImageView imageView = new ImageView(context);
    int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium);
    imageView.setPadding(padding, padding, padding, padding);
    imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    imageView.setImageResource(GalImages[position]);
    ((ViewPager) container).addView(imageView, 0);
    return imageView;
}

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

}

1 个答案:

答案 0 :(得分:0)

向显示drawable的ImageView添加onClickListener

@Override
public Object instantiateItem(ViewGroup container, int position) {
    ImageView imageView = new ImageView(context);
    int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium);
    imageView.setPadding(padding, padding, padding, padding);
    imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    imageView.setImageResource(GalImages[position]);
    ((ViewPager) container).addView(imageView, 0);
     imageView.setOnClickListener(new OnClickListener() {
         @Override
         public void onClick(View v) {
             // do something
         }
    });
    return imageView;
}