2011-03-15 39 views
3

setText()方法在我的應用程序中返回null爲什麼?textView.setText();崩潰

public class GetValue extends Activity { 
    char letter = 'g'; 
    int ascii = letter; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     TextView textView = (TextView)findViewById(R.id.txt_1); 
      textView.setText(ascii); 
    } 
} 

不管我放什麼文本,它總是崩潰。爲什麼setText()保持返回null?

謝謝你,提前

解決方法:在xml文件我的錯誤。我寫道: 機器人:文本= 「@ + ID/txt_1」 當它應該說: 機器人:ID = 「@ + ID/txt_1」

非常感謝所有的答案,評論!

+0

你肯定的伎倆,即TextView的是不是空了嗎?你能提供一個錯誤信息嗎? – janoliver 2011-03-15 21:53:46

+0

可能findViewById()不起作用。你確定你定義了一個叫做txt_1的TextView嗎? – RoflcoptrException 2011-03-15 21:54:00

+0

發佈您的main.xml文件。 – 2011-03-15 21:56:47

回答

8

您試圖將一個整數作爲參數傳遞給setText,該setText假定它是一個資源ID。要顯示計算文本,它作爲一個字符串傳遞:textView.setText("g");

編輯:檢查你的XML文件,我有一些非常基本的測試,它的工作原理

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <TextView 
     android:id="@+id/txt_1" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:text="myTextView"/> 
</LinearLayout> 

也許嘗試清理項目(項目 - >在Eclipse中清理),我最近在最後的ADT版本中遇到了R代的問題。

+0

我試圖把平面文本。我唯一知道的是setText()這行讓我的程序崩潰。我知道這是我的XML文件沒有錯。 logcat表示textView變量返回null。我想我正在使用setText()方法錯誤。 – 2011-03-16 07:05:06

+0

我的回答已更新。 – Hrk 2011-03-16 08:40:47

5

試試這個:

textView.setText(Integer.toString(ascii)); 

另外,還要確保你的佈局XML有TextView的txt_1

2

我已經試過:

Integer.toString(char) and String.valueOf(char) 

都沒有工作。 唯一的解決辦法是:

txt.setText(""+char); 

這不是但從優化一點上是非常有效的,但它確實:)