我正在尝试在gridview中交换图像并制作此代码:
grd.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
counter ++;
if(counter % 1 == 0){
firstclick = position;
data1 = crops.get(position);
}
else if(counter % 2 ==0){
Bitmap swapImage = crops.get(position);
crops.set(position, crops.get(firstclick));
crops.set(firstclick, swapImage);
grd.invalidateViews();
}
}
});
我不明白为什么这段代码不起作用。当我启动我的android时,我点击它们时瓷砖不会交换。我的imageadapter看起来像这样:
public ArrayList<ImageView> pics;
private ArrayList<Bitmap> crops;
private Context mContext;
public ImageAdapter(Context c, ArrayList<Bitmap> crops) {
mContext = c;
this.crops = crops;
}
public int getCount() {
return crops.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageBitmap(crops.get(position));
return imageView;
}
public void getpics(){
for(int i = 0; i<getCount();i++){
ImageView img = new ImageView(mContext);
img.setImageBitmap(crops.get(i));
img.setTag(i);
pics.add(img);
img = null;
}
}
}
首先,我想尝试互相交换图像,然后我想尝试仅在我的bitmaparraylist中交换一个特定的图块。
答案 0 :(得分:2)
counter%1
总是零改变你对这些语句的陈述:
if (counter%2==1) {
....
} else {
...
}
并且对于交换邻居项目,如果计数器从零开始,请执行以下操作:
if (counter % 2 == 1) {
// swap item at counter with item at counter-1
...
}
如果计数器从1开始,请执行以下操作:
if (counter % 2 == 0) {
//swap item at counter with item at counter-1
...
}
答案 1 :(得分:1)
就这样做。
在GridView中,当您想要更改项目时,您只需更改链接到GridView的适配器。
例如,交换两个项目:(GridAdapter extends ArrayAdapter)
GridAdapter adapter = (GridAdapter)gridv.getAdapter();
String firstItem = adapter.getItem(firstPosition);
String secondItem = adapter.getItem(secondPosition);
adapter.remove(firstItem);
adapter.insert(firstItem, secondPosition);
adapter.remove(secondItem);
adapter.insert(secondItem, firstPosition);
&#13;
您还可以通过覆盖getView()来更改自定义适配器中的其他内容。