問題描述
如何在第一次和第二次觸摸時執行不同的事件(TicTacToe for Android) (how to do different event on first and second touch (TicTacToe for Android))
我是在 android 中創建應用程序的初學者,但作為我的第一個項目,我正在嘗試構建一個井字遊戲。但我嘗試在第一次觸摸 Button 並設置 O 時設置 X 已經很長時間了在第二次觸摸。我不知道如何解決這個問題。我認為它應該像我跟隨的那樣工作,但它不是......!這是我的源代碼:
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++;
}
}
參考解法
方法 1:
onClick firstly you set boolean press=true;
so in while loop it always take you into the first if loop
Declare boolean press=true; as a global variable