我的布局有一个 GridView。与 Google 的 API 演示类似,每个网格都有一个图像。此外,我自定义了一个“可绘制图像”,用于突出显示当前选定的项目。当触摸网格的图像时,可以显示“可绘制图像”。不幸的是,当我不触摸网格时它会消失。
我希望 GridView 将继续突出显示所选项目。甚至用户也在滚动屏幕。
从这里,我发现了一些类似的帖子。
但我无法理解他们的方法,他们没有使用自定义图像。谁能给我一些帮助?请。
以下是我的代码:
gridAdapter adapter = new gridAdapter (this, images);
gv = (GridView) findViewById (R.id.gridView1);
gv.setAdapter(adapter);
gv.setSelector(R.drawable.circle);
gv.setDrawSelectorOnTop(true);
以下是我更新的代码:
public class GridViewBasic extends Activity {
Integer[] imageIDs = {
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher };
GridView gridView;
public int lastPos;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(new ImageAdapter(this));
gridView.setSelected(true);
gridView.setSelector(R.drawable.circle);
gridView.setDrawSelectorOnTop(true);
gridView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
lastPos = position;
gridView.setSelection((int)(gridView.getAdapter()).getItemId(lastPos));
System.out.println ("getItemId ="+(gridView.getAdapter()).getItemId(lastPos));
}
});
}
public class ImageAdapter extends BaseAdapter
{
private Context context;
public ImageAdapter(Context c) {
context = c;
}
//---returns the number of images---
public int getCount() {
return imageIDs.length;
}
//---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(185, 185));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(5, 5, 5, 5);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(imageIDs[position]);
return imageView;
}
}
}