2015-10-04 48 views
0

提前感謝時,「無法解析符號」。當在.setText()用於正確類型的Android

我在Android應用程序中有多個TableRow對象,每個對象都包含兩個EditText。我想在打開/關閉應用程序時保存並恢復editTexts的內容和數量,所以我需要設置EditTexts文本的方式,但這是問題所在。

的Android工作室說 「無法解析符號 '的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(""); 
} 

總結一下,我有:

  • 通過tablerow對象總是包含恰好兩個EditTexts

我的問題是:

  • 的Java似乎不承認,我在的EditText要求.setText()

非常感謝提前。

+1

如果您確信'tableRow.getChildAt(1)'返回'EditText',使用強制:'((EditText上)tableRow.getChildAt(1))的setText( 「」);' – Tunaki

回答

1

就像你您鑄造TableRowTableRowHolder的,你需要給孩子View強制轉換爲EditText之前,你可以調用它的方法。

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

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

你可以任意換你的電話裏面如果的instanceof塊以避免任何ClassCastException■如果有任何機會,View可能不是EditText始終。

View child = tableRow.getChildAt(1); 

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

。謝謝你的出色,我從來不知道你可以投出這樣的東西(:,它不會讓我把它標記爲答案(4分鐘) – Beyarkay