2015-10-05 104 views
1

好吧,我正在试图为我正在为一个项目工作的tictactoe游戏设计风格。当我按新游戏时,我想要某种数组将每个Button的背景改变为一种颜色。然后,当用户点击一个按钮使其移动到那里时,该空间将根据玩家的不同而改变为不同的颜色(我有一个PlayerTurn标志变量来决定这一点)。我还想根据与该按钮相对应的索引在int数组中的值。我怎样才能给每个按钮分配一个数值,我以后可以用它来索引到我的数组中?更改背景上的所有按钮点击

这是我目前使用的代码。

Button buttons[] = new Button[9]; 
    buttons[0] = (Button) findViewById(R.id.button0); 
    buttons[1] = (Button) findViewById(R.id.button1); 
    buttons[2] = (Button) findViewById(R.id.button2); 
    buttons[3] = (Button) findViewById(R.id.button3); 
    buttons[4] = (Button) findViewById(R.id.button4); 
    buttons[5] = (Button) findViewById(R.id.button5); 
    buttons[6] = (Button) findViewById(R.id.button6); 
    buttons[7] = (Button) findViewById(R.id.button7); 
    buttons[8] = (Button) findViewById(R.id.button8); 

回答

0

您可以创建类型ButtonArrayList

private ArrayList<Button> mList; 

onCreate()// 
mList = new ArrayList<>(); 
mList.add(yourButton); 
..................... 

for(int i = 0 ; i< mList.size(); i++) 
    mList.get(i).setBackground(//your color); 
+0

好了,我怎么能那么要确保,当我点击,要说中间的按钮,只有该按钮改变颜色。 – Jrawr

+0

我编辑了我的原始文章以显示我正在使用的代码。我不熟悉Arraylist或者他们与Arrays不同。 – Jrawr

+0

你需要使用OnClickListener每个项目 – Lazai