2013-07-26 48 views
2

中的其餘文本我想將文本添加到EditText而不會丟失以前的文本。如何將文本添加到Android

例:打字74時,我想補充的"4"文本框,但不刪除之前輸入的號碼"7"

public void add4() 
{ 
    res = (EditText)findViewById(R.id.editText1); 

    if(res.getText().toString() == "0") 
    { 
     res.setText("4"); 
    } 
    else 
    { 
     // add number 4 to the remaining string 
    }  
} 
+3

使用'append'取代'settext.' – Raghunandan

+0

'res.append( 「4」);' – Houcine

回答

0

res.append("4");或者您可以使用res.setText(res.getText() + "4");

9

您可以使用append方法追加到現有文本。

res.append("4"); 

http://developer.android.com/reference/android/widget/TextView.html#append(java.lang.CharSequence)

(作爲一個方面說明,不要用==比較字符串,使用.equals()

+3

我希望你不介意我添加一個側面說明在這裏。爲了避免出現'NullPointerException',你應該總是在對象上運行'.equals',你肯定它是一個字符串......就像'「0」.equals(res.getText()。toString())' –

2

試試這個:

我用.equals方法的字符串對象以避免NullPointerException如果對象爲空或不是字符串可能發生。

public void add4() { 

    res = (EditText)findViewById(R.id.editText1); 

    if("0".equals(res.getText().toString())) 
    { 
     res.setText("4"); 
    } 
    else 
    { 
     res.append("4"); 
    }  
}