Chess - GridView , How to move chess piece by two

2019-06-09 09:39发布

问题:

I am working with a chess app which loads chess position from FEN Notations

Basic information about what I did..

I used Gridview of 64 Imageviews and set chessboard image as a background image of Gridview.I able to load the chess position in Gridview.But I dont know how to move the chess piece from current location (first click) to new location (second click). but I have the two positions from onclick of my CustomAdapter.

I am new to android and gridview

回答1:

I have stored the position of two imageviews from two clicks in MyApplication
those I got from onclick.

 public class MyApplication extends Application {

    private int ClickedImageView1=-1;
    private int ClickedImageView2=-1;

private static MyApplication instance = new MyApplication();

// Getter-Setters
public static MyApplication getInstance() {
    return instance;
}
public static void setInstance(MyApplication instance) {
    MyApplication.instance = instance;
}


public void setClickedImageView1(int ClickedImageView1) {
    this.ClickedImageView1 = ClickedImageView1;
}

public int getClickedImageView1() {
    return ClickedImageView1;
}

public void setClickedImageView2(int ClickedImageView2) {
    this.ClickedImageView2 = ClickedImageView2;
}

public int getClickedImageView2() {
    return ClickedImageView2;
}
}

Also in the CustomAdapter class, in OnClickListener added some codes

  public void onClick(View v) {


                if (MyApplication.getInstance().getClickedImageView1()== -1) {
                    MyApplication.getInstance().setClickedImageView1(position);  
           //saving the first click position    if it is first click      
                }
                else {
                    MyApplication.getInstance().setClickedImageView2(position);  
        //saving the second click position                                               
                    ImagesId[MyApplication.getInstance().getClickedImageView2()]=ImagesId[MyApplication.getInstance().getClickedImageView1()]; 
              //moving image to secondclick position
                    ImagesId[MyApplication.getInstance().getClickedImageView1()]=0; //clear the imageview1
                    gridView.setAdapter(new CustomAdapter(MainActivity.this,ImagesId));     //reloads the adapter   
             // gridView.setBackgroundResource(R.drawable.chessboard);
                    MyApplication.getInstance().setClickedImageView1(-1);
                    MyApplication.getInstance().setClickedImageView2(-1);
                    //resetting the varibles in MyApplication object
                }

it is working!!!