如何更改多个按钮中的文本?

How to change the text within multiple buttons?

我正在尝试将 c# windows 表单程序转换为 android,但我正处于最后一块,我似乎无法理解其翻译。

我在框架布局中有 9 个按钮,我需要通过迭代或一次抓取所有按钮来删除文本。

在我原来的程序中,我使用了这样的 foreach 循环:

foreach(control boardPosition in gameBoard)
{
    ((Button) boardPosition).Text ="";
    ((Button) boardPosition).ForeColor = Color.Black;
}

这是我目前得到的

FrameLayout GameBoard = (FrameLayout) findViewById(R.id.GameBoard)

for(Button boardPosition : GameBoard)
{
    boardPosition.setText("");
    boardPosition.setTextColor(Color.BLACK);        
}

我收到的错误只是 "foreach not applicable to type 'android.widget.Framelayout' "但我不确定它是什么替代品,或者是否有替代品。

您要循环的对象必须实现可迭代接口。 Java 必须知道它可以通过某种方式进行迭代。 FrameLayout 不可迭代。它不知道你的意图,你里面有一堆按钮。

为了循环布局中的每个按钮,我会使用这样的东西:

    FrameLayout layout = (FrameLayout) view.findViewById(R.id.frame);
    int children = layout.getChildCount();
    for (int i = 0; i < children; i++) {
        View view = layout.getChildAt(i);
        if (view instanceof Button) {
            ((Button) view).setText("");
            ((Button) view).setTextColor(Color.BLACK);
        }
    }

如果你还想使用foreach循环,你必须扩展FrameLayoutclass并实现Iterable接口。但这比白做更多。