简体   繁体   中英

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

thanks in advance.

I have multiple TableRow objects in an Android app, each of which contains exactly two EditTexts. I want to have the contents and quantity of editTexts saved and restored when I open/close the app and so I need to have a way to set the text of the EditTexts, but this is where the problem is.

Android Studio is saying "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("");
}

To recap, I have:

  • A tableRow object always containing exactly two EditTexts

and my problem is that:

  • Java seems to not recognise that I am asking for .setText() on a EditText

Thanks so much in advance.

Just like you're casting your TableRow out of the TableRowHolder , you need to cast the View child to an EditText before you can call its methods.

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

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

You could optionally wrap your calls inside an instanceof if-block to avoid any ClassCastException s if there's any chance that the View may not be an EditText always.

View child = tableRow.getChildAt(1);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM