对于井字游戏应用程序,我在3 X 3网格中有9个按钮。下面是从board_layout.xml的前三个按钮的代码 - ),这个屏幕上设置此布局和初始化按钮如下安卓按钮已初始化,但无法正常工作
<TableLayout
android:id="@+id/tableLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="20sp" >
<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center" >
<Button
android:id="@+id/cellOne"
android:layout_width="90sp"
android:layout_height="98sp"
android:text=""
android:textSize="70sp"
/>
<Button
android:id="@+id/cellTwo"
android:layout_width="90sp"
android:layout_height="98sp"
android:text=""
android:textSize="70sp"
/>
<Button
android:id="@+id/cellThree"
android:layout_width="90sp"
android:layout_height="98sp"
android:text=""
android:textSize="70sp"
/>
</TableRow>
<!and so on for other 6>
现在在我的MainActivity.java我有一个函数setboard(:
private String p1name = "P1";
private String p2name = "P2";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void setName(View view) {
//Function called upon click on some button
// Other code irrelevant to the question
setBoard();
}
}
public void setBoard() {
////////////
LayoutInflater inflater = this.getLayoutInflater();
View boardView = inflater.inflate(R.layout.board_layout, null);
////////////
boardCells = new Button[3][3];
boardCells[0][0] = (Button) boardView.findViewById(R.id.cellOne);
boardCells[0][1] = (Button) boardView.findViewById(R.id.cellTwo);
boardCells[0][2] = (Button) boardView.findViewById(R.id.cellThree);
// Code for other 6 buttons
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++) {
boardCells[i][j].setOnClickListener(new MyClickListener(i, j));
boardCells[i][j].setText("");
boardCells[i][j].setEnabled(false);
}
setContentView(R.layout.board_layout);
TextView tv1 = (TextView) findViewById(R.id.p1Name_board);
tv1.setText(p1name + ":");
tv1 = (TextView) findViewById(R.id.p2Name_board);
tv1.setText(p2name + ":");
turnDisp = (TextView) findViewById(R.id.turnDispString);
turnDisp.setText("Turn of " + p1name);
}
下面是MyClickListener类的代码(内部类MainActivity类别的):
class MyClickListener implements View.OnClickListener {
int x;
int y;
public MyClickListener(int x, int y) {
this.x = x;
this.y = y;
//This Log.d works fine
Log.d("TAG1", Float.toString(x) + " " + Float.toString(y));
}
public void onClick(View view) {
//This Log.d doesn't work
Log.d("TAG2", Float.toString(this.x) + " Hi ");
//This Toast also doesn't work
Toast.makeText(getApplicationContext(), "Pressed", Toast.LENGTH_LONG).show();
//Plus Other code irrelevant to the question
}
现在的问题是,在Log.d构造方法中调用,同时设置按钮为w操作正常并打印到Logcat,但点击按钮时onClick函数不起作用。 onClick函数不显示Log.d和toast。
任何帮助,将不胜感激。
数组索引为零,顺便 –
什么的'膨胀()'调用其他解决?您是否将电路板直接膨胀到现有布局?如果不是,那么将充气板添加到现有布局的哪个位置?你确定你正在设置听众的'View'实际上是屏幕上的电路板吗? –
尝试使用'@Override public void onClick'来强制编译器使用该方法 –