在Java代码中引用XML变量时出现Android错误

在Java代码中引用XML变量时出现Android错误,java,android,xml,variables,Java,Android,Xml,Variables,在java代码中引用XML变量时出错。请帮忙 我的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

在java代码中引用XML变量时出错。请帮忙

我的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>

请帮忙。提前感谢。

在调用findViewById之前,您应该先调用setContentView。否则,由于调用findViewById时不会加载XML,因此它无法找到id。

在调用findViewById之前,应该调用setContentView。否则,由于调用findViewById时不会加载XML,因此它无法找到id。

这是一个常见错误,Julien的回答应该可以解决这个问题。一般来说,我总是将setContenView放在super.onCreate之后。当你发布一个问题说你在做某事时“出错”时,说出错误是什么总是有帮助的。这是一个常见的错误,Julien的回答应该可以解决问题。一般来说,我总是将setContenView放在super.onCreate之后。当你发布一个问题说你在做某事时“出错”时,说出错误是什么总是有帮助的。
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);

    }
}