我有一个使用本教程GridView Android创建的gridview,它运行得很好。现在我想将图像叠加到gridview的项目上,如果单击该项目的话。我不知道如何做到这一点,无论我使用另一个gridview并合并它们还是只有很多图像视图:s。只是为了澄清这个问题:如何叠加到gridview项目上?提前谢谢!
答案 0 :(得分:3)
因此,有几种方法可以实现这一目标,但最灵活的方法是在getView
方法中使用自定义视图。
在ImageAdapter类中添加LayoutInflater:
private LayoutInflater mInflater;
在构造函数中初始化它:
public ImageAdapter(Context c) {
mContext = c;
// Initialise the inflater
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
这用于膨胀xml视图,例如:
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="@+id/mainImage"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<ImageView
android:id="@+id/overlayImage"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:visibility="gone"
/>
</RelativeLayout>
在ImageAdapter类getView
方法
public View getView(int position, View convertView, ViewGroup parent) {
// RelativeLayout as used in the xml view
RelativeLayout customView;
if (convertView == null) { // if it's not recycled, inflate
customView = (RelativeLayout) mInflater.inflate(R.layout.customview, null);
} else {
imageView = (RelativeLayout) convertView;
}
// Get the mainImageView from the parent
ImageView mainImage = (ImageView) customView.findViewById(R.id.mainImage);
imageView.setImageResource(mThumbIds[position]);
// Overlay view
ImageView overlayImage = (ImageView) customView.findViewById(R.id.overlayImage);
overlayImage.setImageResource(mOverlayThumbIds[position]); // new array containing overlay references
return customView;
}
然后点击
显示叠加图像gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
ImageView overlayImage = (ImageView) v.findViewById(R.id.overlayImage);
overlayImage.setVisibility(View.VISIBLE);
}
});
这是一个非常基本的例子,但希望你会发现这种方法很有用。