如何在第一次和第二次触摸时执行不同的事件(TicTacToe for Android)

how to do different event on first and second touch (TicTacToe for Android)

我是在 android 中创建应用程序的初学者,但作为我的第一个项目,我正在尝试构建一个 TicTacToe 游戏..但是我花了很长时间尝试在按钮时设置 X被第一次触摸并在第二次触摸时设置 O。我不知道如何解决这个问题。 我认为它应该像我所做的那样工作,但它不是......! 这是我的源代码:

public class MainActivity extends Activity implements OnClickListener{

private Button b1,b2,b3,b4,b5,b6,b7,b8,b9;

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

    b1=(Button) findViewById(R.id.button1);
    b1.setOnClickListener(this);

    b2=(Button) findViewById(R.id.button2);
    b2.setOnClickListener(this);

    b3=(Button) findViewById(R.id.button3);
    b3.setOnClickListener(this);

    b4=(Button) findViewById(R.id.button6);
    b4.setOnClickListener(this);

    b5=(Button) findViewById(R.id.button10);
    b5.setOnClickListener(this);

    b6=(Button) findViewById(R.id.button11);
    b6.setOnClickListener(this);

    b7=(Button) findViewById(R.id.button7);
    b7.setOnClickListener(this);

    b8=(Button) findViewById(R.id.button8);
    b8.setOnClickListener(this);

    b9=(Button) findViewById(R.id.button5);
    b9.setOnClickListener(this);
}

public void onClick(View v)
{
    boolean press=true;
    int i=0;
    while(i<9){     
            if(press==true)
            {
                if((Button)v==b1)
                {
                    b1.setText("X");
                    press=false;
                }

                else if((Button)v==b2)
                {
                    b2.setText("X");
                    press=false;
                }

                else if((Button)v==b3)
                {
                    b3.setText("X");
                    press=false;
                }

            }

            if(press==false)
            {
                if((Button)v==b1)
                {
                    b1.setText("O");
                    press=true;
                }
                else if((Button)v==b2)
                {
                    b2.setText("O");
                    press=true;
                }
                else if((Button)v==b3)
                {
                    b3.setText("O");
                    press=true;
                }
            }
            i++;
    }
}

onClick 首先你设置 boolean press=true; 所以在 while 循环中它总是带你进入第一个 if loop

声明boolean press=true; as a global variable