2011-03-13 82 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。

相关问题