我在我的应用程序中使用PagerAdaper进行图像幻灯片。我想在它上面添加监听器意味着如果图像显示我点击它时它会说些什么。假设我有一个苹果的图像现在我想在它上面添加监听器当它点击它说苹果。我想在所有原始文件上添加相同的内容。
package com.example.slider;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ImageAdapter extends PagerAdapter {
private Context mcontext;
private int[] myImages = new int[] {R.raw.one , R.raw.two, R.raw.three,
R.raw.four , R.raw.five , R.raw.six, R.raw.seven, R.raw.eight,
R.raw.nine, R.raw.ten, R.raw.eleven, R.raw.twele , R.raw.thirteen, R.raw.fourteen,
R.raw.fifteen, R.raw.one_image, R.raw.two_image,
R.raw.three_image, R.raw.four_image, R.raw.five_image,
R.raw.six_image, R.raw.seven_image};
ImageAdapter(Context context){
mcontext = context;
}
@Override
public int getCount() {
return myImages.length;
}
@Override
public boolean isViewFromObject(View view, Object o) {
return view == o;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(mcontext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageResource(myImages[position]);
container.addView(imageView,0);
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position,Object object) {
container.removeView((ImageView)object);
}
}
有几种不同的可能解决方案。使用HashMap将每个视图与其图像资源连接的一种方法。
public class ImageAdapter extends PagerAdapter {
private Context mcontext;
private int[] myImages = new int[] {R.raw.one , R.raw.two, R.raw.three,
R.raw.four , R.raw.five , R.raw.six, R.raw.seven, R.raw.eight,
R.raw.nine, R.raw.ten, R.raw.eleven, R.raw.twele , R.raw.thirteen, R.raw.fourteen,
R.raw.fifteen, R.raw.one_image, R.raw.two_image,
R.raw.three_image, R.raw.four_image, R.raw.five_image,
R.raw.six_image, R.raw.seven_image};
ImageAdapter(Context context){
mcontext = context;
}
private HashMap<View, Integer> viewToImageResource = new HashMap<>();
private View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Integer clickedImageResource = viewToImageResource.get(v);
// Do something with clickedImageResource
}
};
@Override
public int getCount() {
return myImages.length;
}
@Override
public boolean isViewFromObject(View view, Object o) {
return view == o;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(mcontext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageResource(myImages[position]);
container.addView(imageView,0);
viewToImageResource.put(container, myImages[position]);
container.setOnClickListener(clickListener);
return imageView;
}
@Override
public void destroyItem(ViewGroup container, int position,Object object) {
container.removeView((ImageView)object);
}
}