我使用网格视图使用Glide显示图像。如何在网格中高亮显示所选图像?此外,我需要限制用户只选择一个图像,如果用户再点击一个图像,则应取消选择第一个图像。
这是我的xml文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<GridView
android:id="@+id/galleryGridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnWidth="280dp"
android:gravity="center"
android:horizontalSpacing="2dp"
android:numColumns="3"
android:padding="2dp"
android:stretchMode="columnWidth"
android:verticalSpacing="2dp"
android:listSelector="@drawable/selected_grid">
</GridView>
</RelativeLayout>
和Java代码
GridView gallery = (GridView) findViewById(R.id.galleryGridView);
gallery.setAdapter(new ImageAdapter(this));
gallery.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// Help me here
}
});
}
适配器
private class ImageAdapter extends BaseAdapter {
/** The context. */
private Activity context;
/**
* Instantiates a new image adapter.
*
* @param localContext
* the local context
*/
public ImageAdapter(Activity localContext) {
context = localContext;
images = getAllShownImagesPath(context);
}
public int getCount() {
return images.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
if (convertView == null) {
picturesView = new ImageView(context);
picturesView.setScaleType(ImageView.ScaleType.FIT_CENTER);
picturesView
.setLayoutParams(new GridView.LayoutParams(270, 270));
} else {
picturesView = (ImageView) convertView;
}
Glide.with(context).load(images.get(position))
.placeholder(R.mipmap.ic_launcher).centerCrop()
.into(picturesView);
return picturesView;
}
答案 0 :(得分:0)
您可以通过类似的方式进行管理
gallery.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
for(int i = 0; i < arg0.getChildCount(); i++)
{
if(i == position)
arg0.getChildAt(i).setBackgroundColor(Color.BLUE);
else
arg0.getChildAt(i).setBackgroundColor(Color.TRANSPARENT);
}
}
});
或第二种方式只是为gridview做一个简单的选择器
list_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="false" android:drawable="@color/yourcolor" />
<item android:drawable="@color/transparent" />
</selector>
并设置gridview的listSelector,如
android:listSelector="@drawable/list_selector"