2014-05-08 28 views
0

我正在學習如何開發面向android的應用程序。使用XML佈局文件而不是Java代碼創建TextView以顯示通過意圖接收的消息

我按照Google的教程Building Your First App

這個想法基本上是在一個片段中寫入一條消息,用一個按鈕提交它,該消息通過intent傳遞並顯示在第二個片段中。

我的問題是關於我們顯示消息的部分。這是它是如何在本教程中完成:

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

    // Get the message from the intent 
    Intent intent = getIntent(); 
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE); 

    // Create the text view 
    TextView textView = new TextView(this); 
    textView.setTextSize(40); 
    textView.setText("You submitted: "+message); 


    // Set the text view as the activity layout 
    setContentView(textView); 

} 

我瞭解到,UI組件可以實現使用XML或Java,在這種情況下顯然教程使用Java,使通過接收到的數據的新的TextView intent。我試圖重做那部分,但是這一次,在涉及到視圖時,沒有太依賴於Java。所以,我更換了部分// Create the text view下通過:

TextView textView = (TextView) findViewById(R.id.display_message); 
textView.setText(message); 

而在fragment_display_message.xml我有以下元素:

<TextView 
    android:id="@+id/display_message" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@string/hello_world" /> 

它拋出一個NullPointerExceptiontextView.setText(message);

我不知道爲什麼會這樣,爲什麼不能這樣做嗎?

回答

1

我想你應該叫

setContentView(R.layout.fragment_display_message); 

你叫

TextView textView = (TextView) findViewById(R.id.display_message); 
textView.setText(message); 

但它是一個片段之前?

+0

這工作!是的,它是一個片段。你能向我解釋爲什麼這種方式有效嗎? –

+0

實際上它現在是有意義的。因爲我們沒有通過Java代碼創建TextView,所以我們無法將它設置爲ContentView。 –

+0

AFAIK,當您調用findViewById時,它將搜索您用於您應用的當前contentview,並且如果您從未設置任何視圖,它將返回null。所以不要忘記在findViewById之前調用setContentView:D – TqT

相關問題