2011-03-13 73 views
0

在Java代碼中引用XML變量時出現錯誤。請幫忙。在Java代碼中引用XML變量時出現Android錯誤

我的XML代碼

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:id="@+id/root" 
    > 

<LinearLayout 

    android:id="@+id/llayout1" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
<TextView 
    android:id="@+id/tv" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 


    />  
</LinearLayout> 

</RelativeLayout> 

我的Java代碼

package com.motivational.wallpapers; 

import android.app.Activity; 
import android.os.Bundle; 
import android.widget.LinearLayout; 
import android.widget.TextView; 
import android.util.Log; 


public class wallpaper_activity extends Activity { 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     TextView tv = (TextView)findViewById(R.id.tv); 
     Log.v("hello","tv value : " +tv); 
     tv.setText(" There are many ways of doing things"); 
     Log.d("hello","tv value : " +tv); 
     setContentView(R.layout.main); 

    } 
} 

請幫助。提前致謝。

+0

這是一個常見的錯誤,朱利安的答案應該解決這個問題。一般來說,我總是在super.onCreate之後立即放置setContenView。 – Squonk 2011-03-13 22:38:08

+0

當你發佈一個問題,說當你做某事時你「有錯誤」時,說錯誤是什麼總是有幫助的。 – 2011-03-14 00:03:50

回答

4

在調用findViewById之前,您應該調用setContentView。否則,由於XML在調用findViewById時不會被加載,所以它無法找到該id。

相關問題