我正在尝试制作记忆游戏但是当我按下x
按钮时,我无法找到更改y
按钮的方法。这是我的代码。
我希望能够在使用私有空gridButtonClicked
时处理不同的按钮。
public class MainActivity2 extends ActionBarActivity {
private static final int NUM_ROWS =10 ;
private static final int NUM_COLS = 4;
Button buttons[][]=new Button[NUM_ROWS][NUM_COLS];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
populateButtons();
}
private void populateButtons() {
TableLayout table = (TableLayout) findViewById(R.id.tableForButtons);
for(int row=0; row < NUM_ROWS; row++){
TableRow tableRow=new TableRow(this);
tableRow.setLayoutParams(new TableLayout.LayoutParams( //we use this to fill the screen
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.MATCH_PARENT,
1.0f));
table.addView(tableRow);
for(int col=0; col < NUM_COLS; col++){
final int FINAL_COL=col;
final int FINAL_ROW=row;
Button button= new Button(this);
button.setLayoutParams(new TableRow.LayoutParams( //we use this to fill the screen
TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.MATCH_PARENT,
1.0f));
button.setText("" + col + "," + row); //text for every button
button.setPadding(0,0,0,0); //this is to make text visible even if the buttons are very small
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
gridButtonClicked(FINAL_COL,FINAL_ROW); //we need final because we can't pass variables from inner classes
}
});
tableRow.addView(button);
buttons[row][col]=button;
}
}
}
private void gridButtonClicked(int col, int row) {
Toast.makeText(this,"clicked",Toast.LENGTH_SHORT).show();
Button button=buttons[row][col];
// button.setBackgroundResource(R.drawable.abc_ab_share_pack_mtrl_alpha);
String id= (String) button.getText();
if(id.equals("1,2")) {
button.setText("" + col + ""); //change the button
}
if(id.equals("1")) {
button.setText("" + col + "," + row); //change the button
}
if(id.equals("2,1")) {
button.setText("" + col + ""); //change the button
}
}
任何帮助都将不胜感激。
答案 0 :(得分:0)
我的建议是创建自己的视图(您也可以从Button或ImageButton扩展)并使用适配器填充GridView。
之后,您可以在其班级上控制行为或视图。
答案 1 :(得分:0)
我认为这就是你要找的东西。它与第一个按钮的交互方式相同。如果我误解了您的问题,或者您需要更多信息,请告诉我们!
private void gridButtonClicked(int col, int row) {
Toast.makeText(this,"clicked",Toast.LENGTH_SHORT).show();
Button button=buttons[row][col];
int otherRow = ?;
int otherColumn = ?;
Button otherButton = buttons[otherRow,otherColumn];
otherButton.setText("Whatever you want");
// button.setBackgroundResource(R.drawable.abc_ab_share_pack_mtrl_alpha);
String id= (String) button.getText();
if(id.equals("1,2")) {
button.setText("" + col + ""); //change the button
}
if(id.equals("1")) {
button.setText("" + col + "," + row); //change the button
}
if(id.equals("2,1")) {
button.setText("" + col + ""); //change the button
}
}