"Cannot Resolve Symbol" 当 .setText() 用于正确类型的子项时 Android

"Cannot Resolve Symbol" when .setText() used on a child of correct type Android

提前致谢。

我在 Android 应用程序中有多个 TableRow 对象,每个对象恰好包含两个 EditText。我想在我 open/close 应用程序时保存和恢复 editTexts 的内容和数量,所以我需要有一种方法来设置 EditTexts 的文本,但这就是问题所在。

Android 工作室说 "Cannot Resolve Symbol 'setText'":

//will loop through each of the TableRows in a tableRowHolder(no problem yet):
for (int i = 0; i < tableRowHolder.getChildCount() && tableRowHolder.getChildAt(i) instanceof android.widget.TableRow; ++i) { 

    //set tableRow to be the i-th child in tableRowHolder (no problem yet)
    TableRow tableRow = (TableRow) tableRowHolder.getChildAt(i);

    //where the problem is("setText" is red), I don't think Java recognises that "tableRow.getChildAt(1)" is an EditText, even though it always will be.
    tableRow.getChildAt(1).setText();

    //this however, is perfectly fine:
    EditText et = new EditText(
    et.setText("");
}

回顾一下,我有:

我的问题是:

提前致谢。

就像将 TableRowTableRowHolder 中转换出来一样,您需要先将 View 子对象转换为 EditText,然后才能调用其方法.

TableRow tableRow = (TableRow) tableRowHolder.getChildAt(i);

((EditText) tableRow.getChildAt(1)).setText("Some Text");

您可以选择将调用包装在 instanceof if-block 中,以避免在 View 可能不存在时出现任何 ClassCastExceptions总是EditText

View child = tableRow.getChildAt(1);

if (child instanceof EditText) {
    EditText et = (EditText) child;
    et.setText("Some Text");
}