我在生成多个按钮并添加一些属性时遇到问题。我试图在屏幕上显示100个小按钮,每当我点击其中一个按钮时,它应该将其文本更改为" X"。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout);
GridLayout buttLayout = (GridLayout) findViewById(R.id.buttLayout);
for (int i = 1; i < 100; i++) {
LinearLayout.LayoutParams parameters = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
final Button bet = new Button(this);
bet.setHeight(5);
bet.setWidth(5);
bet.setText("");
bet.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
bet.setText("X");
}
});
buttLayout.addView(bet, parameters);
}
}
和XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<GridLayout
android:layout_width="match_parent"
android:layout_height="400dp"
android:orientation="horizontal"
android:gravity="left"
android:id="@+id/buttLayout"
android:columnCount="10"
android:rowCount="10">
</GridLayout>
</LinearLayout>
我非常确定这是一种更好的方法,但我刚刚开始使用Android / Java进行编程,而且无法找到更好的方法。任何帮助,将不胜感激。感谢
答案 0 :(得分:1)
您只需要在循环中设置按钮
OnClickListener OnButtonClick = new OnButtonClick();
GridLayout buttLayout = (GridLayout) findViewById(R.id.buttLayout);
LinearLayout.LayoutParams parameters = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
for (int i = 1; i < 100; i++) {
final Button bet = new Button(this);
bet.setHeight(5);
bet.setWidth(5);
bet.setText("");
bet.setOnClickListener(OnButtonClick);
buttLayout.addView(bet, parameters);
}
}
//点击所有按钮的监听器
public class OnButtonClick implements View.OnItemClickListener{
public void onClick(View v) {
bet.setText("X");
}
}