简体   繁体   English

如何在GridView(Android)中交换图像

[英]How to swap images in a GridView (Android)

I'm working on a slider puzzle Android app, so I'm using a GridView to display 16 images representing tiles. 我正在开发一个滑动拼图Android应用程序,所以我使用GridView来显示代表图块的16个图像。 One of the tiles will consist of a plain white image (representing the background). 其中一个图块将由纯白图像(代表背景)组成。 The idea is that if the user clicks on any tile neighboring the white tile, the selected tile and the white tile will switch positions. 这个想法是,如果用户点击与白色瓷砖相邻的任何瓷砖,则所选瓷砖和白色瓷砖将切换位置。

I'm trying to implement this by setting the white tile to the tile selected by the user, and vice versa. 我试图通过将白色图块设置为用户选择的图块来实现此功能,反之亦然。 I saved the position of the white tile (it starts off at position 15) in the variable masterTilePos, and using the ImageAdapter Integer array referring to the images in my R.drawable file, set the image at masterValPos to the image at the selected index, and the selected image to the white tile. 我在变量masterTilePos中保存了白色瓷砖的位置(从位置15开始),并使用参考R.drawable文件中图像的ImageAdapter Integer数组,将masterValPos处的图像设置为所选索引处的图像,并将所选图像添加到白色图块。 However, when I run the program, the tiles only successfully switch the first time: after that, it doesn't work properly and the order of the tiles within the GridView is ruined. 但是,当我运行程序时,磁贴只能在第一次成功切换:之后,它无法正常工作,GridView中的磁贴顺序也会被破坏。 I think it may because the array is simply referring to the actual image objects, but I'm not sure how to what to do instead; 我想这可能是因为数组只是指实际的图像对象,但我不知道该怎么做呢? it has already been three days since I ran into this problem. 我遇到这个问题已经有三天了。 Here is my code: 这是我的代码:

//GRID VIEW

public class MainActivity extends ActionBarActivity { 

int masterTilePos = 15;
GridView gridview;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    gridview = (GridView) findViewById(R.id.gridview);
    gridview.setAdapter(new ImageAdapter(this));

    gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View v,
                                int position, long id) {

 //These methods check if a neighboring tile is white, if there is one,  swap() is called

   if(checkUp(position) || checkDown(position) || checkLeft(position) || checkRight(position)) { 

                swap(position);

            }

        }
    });


}


  public void swap(int pos) {

    ImageAdapter updater = new ImageAdapter(this);

  //This is where I try to switch the images, and seems to be the source of the problem

    int val = updater.mThumbIds[masterTilePos];
    updater.mThumbIds[masterTilePos] = updater.mThumbIds[pos];  
    updater.mThumbIds[pos] = val;

    updater.notifyDataSetChanged();
    gridview.setAdapter(updater);
    gridview.invalidateViews();

    masterTilePos = pos;

  }

}




//IMAGE ADAPTER


public class ImageAdapter extends BaseAdapter {

private Context mContext;


public ImageAdapter(Context c) {

    mContext = c;


}

public int getCount() {

    return mThumbIds.length;
}

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

        DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();

        int width = metrics.widthPixels / 4;
        int height = metrics.heightPixels / 4;


        imageView = new ImageView(mContext);

        imageView.setLayoutParams(new GridView.LayoutParams(width, height));

        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setPadding(1, 1, 1, 1);
    }

    else {

        imageView = (ImageView) convertView;
    }

    imageView.setImageResource(mThumbIds[position]);
    return imageView;
}

// the array containing references to the images

public Integer[] mThumbIds = {


        R.drawable.pic1,
        R.drawable.pic2,
        R.drawable.pic3,
        R.drawable.pic4,
        R.drawable.pic5,
        R.drawable.pic6,
        R.drawable.pic7,
        R.drawable.pic8,
        R.drawable.pic9,
        R.drawable.pic10,
        R.drawable.pic11,
        R.drawable.pic12,
        R.drawable.pic13,
        R.drawable.pic14,
        R.drawable.pic15,
        R.drawable.background


  };

}

Can anyone please help me solve this so I can successfully switch the images within the grid? 任何人都可以帮我解决这个问题,这样我就能成功切换网格中的图像吗? Thanks. 谢谢。

In onCreate you are doing: 在onCreate你正在做:

gridview.setAdapter(new ImageAdapter(this));

So, you created adapter, without assign it to any variable. 因此,您创建了适配器,而没有将其分配给任何变量。 This is wrong! 这是错的!

Then, every swap you create new Adapter: 然后,每次交换你创建新的适配器:

ImageAdapter updater = new ImageAdapter(this);

And you are setting it as current adapter: 并且您将其设置为当前适配器:

gridview.setAdapter(updater);

This is wrong as well. 这也是错误的。

You must do in such a way: 你必须这样做:

  1. OnCreate -> create adapter, assign it to objects's variable (property) OnCreate - >创建适配器,将其分配给对象的变量(属性)
  2. Then you need to work only with that variable. 然后你只需要使用那个变量。

And then, if you have a problem, debug your logic in SWAP method. 然后,如果遇到问题,请在SWAP方法中调试逻辑。

    //GRID VIEW

public class MainActivity extends ActionBarActivity { 

int masterTilePos = 15;
GridView gridview;
ImageAdapter imageAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    gridview = (GridView) findViewById(R.id.gridview);
    imageAdapter= new ImageAdapter(this);
    gridview.setAdapter(imageAdapter);

    gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View v,
                                int position, long id) {

 //These methods check if a neighboring tile is white, if there is one,  swap() is called

   if(checkUp(position) || checkDown(position) || checkLeft(position) || checkRight(position)) { 

                swap(position);

            }

        }
    });


}


  public void swap(int pos) {

  //This is where I try to switch the images, and seems to be the source of the problem

    int val = imageAdaptor.mThumbIds[masterTilePos];
    imageAdapter.mThumbIds[masterTilePos] = imageAdapter.mThumbIds[pos];
    imageAdapter.mThumbIds[pos] = val;

    imageAdapter.notifyDataSetChanged();
    gridview.invalidateViews();

    masterTilePos = pos;
  }
}

//IMAGE ADAPTER

public class ImageAdapter extends BaseAdapter {

private Context mContext;

public ImageAdapter(Context c) {
    mContext = c;
}

public int getCount() {
    return mThumbIds.length;
}

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
        DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();

        int width = metrics.widthPixels / 4;
        int height = metrics.heightPixels / 4;

        imageView = new ImageView(mContext);

        imageView.setLayoutParams(new GridView.LayoutParams(width, height));

        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
        imageView.setPadding(1, 1, 1, 1);
    }

    else {
        imageView = (ImageView) convertView;
    }

    imageView.setImageResource(mThumbIds[position]);
    return imageView;
}

// the array containing references to the images

public Integer[] mThumbIds = {
        R.drawable.pic1,
        R.drawable.pic2,
        R.drawable.pic3,
        R.drawable.pic4,
        R.drawable.pic5,
        R.drawable.pic6,
        R.drawable.pic7,
        R.drawable.pic8,
        R.drawable.pic9,
        R.drawable.pic10,
        R.drawable.pic11,
        R.drawable.pic12,
        R.drawable.pic13,
        R.drawable.pic14,
        R.drawable.pic15,
        R.drawable.background
  };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM