我正在使用 TableLayout 和 TableRow 创建 6/6 网格按钮。
private Button myButton;
private static final int a=7;
private static final int b=7;
private void createLayoutDynamically() {
won = (TableLayout)findViewById(R.id.won);
for ( int qq = 1; qq < a; qq++) {
TableRow tableRow = new TableRow(this);
tableRow.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.MATCH_PARENT,
2
));
won.setPadding(20,20,20,20);
won.addView(tableRow);
for ( int q = 1; q < b; q++) {
myButton = new Button(this);
}
}
}
我还实现了 CounDownTimme,当时间结束时,我想禁用网格中所有按钮的 onclick。
public void inittimer(){
lol =new CountDownTimer(czass, 100) {
public void onTick(long millisUntilFinished) {
czass = millisUntilFinished;
czas.setText("" + millisUntilFinished / 1000);
}
public void onFinish() {
layout2.setVisibility(View.VISIBLE);
for ( int i = 0; i < won.getChildCount(); i++ ){
View view = won.getChildAt(i);
view.setEnabled(false);
}
}
}.start();
}
所以我得到了我所有的网格 child ,但是当时间结束时我仍然可以点击这个按钮。为什么他们没有残疾?你能帮我吗?
<小时/>解决方案:
需要明确的是,我更正了 @matiash 的代码以适合我的代码:
Button buttons [][]= new Button[a][b];
for (int i=1;i<buttons.length;i++) {
for (int j=1;j<buttons[i].length;j++) {
Button btn = buttons[i][j];
btn.setEnabled(false);
}
}
这做同样的事情,但适合我发布的代码。有人能派上用场吗?
最佳答案
TableLayout
的 subview 是您添加的各种 TableRow
,而不是按钮本身。
您可以更改此代码以迭代 TableLayout
的所有“孙子”,但我建议使用更简单的替代方案:保留您添加的所有按钮的列表,然后对其进行迭代。例如:
mAllButtons = new ArrayList<Button>();
for ( int q = 1; q < b; q++) {
myButton = new Button(this);
mAllButtons.add(myButton);
}
然后,稍后:
for (Button b : mAllButtons)
b.setEnabled(false);
关于java - 为什么我不能为动态创建的按钮设置启用(假),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23975360/