findViewById在调用setContentView后返回null

时间:2012-12-25 07:34:41

标签: android textview findviewbyid

我尝试通过findViewById(int)在我的java文件中引用TextView,但是即使在使用正确的布局文件调用setContentView(int)之后,这似乎也返回null。

Help.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TextView
    android:id="@+id/tvBoxHelp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/help"
    android:layout_gravity="center"
    android:textSize="20sp" />

</LinearLayout>

Help.java

 public class Help extends Activity {

private TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    setContentView(R.layout.help);
    tv = (TextView) findViewById(R.id.tvBoxHelp);
    tv.setText("text");
    super.onCreate(savedInstanceState);
    }
  }

提前致谢。

3 个答案:

答案 0 :(得分:4)

您的super.onCreate(savedInstanceState);位置导致问题。

用这个

替换你的Help.java
public class Help extends Activity {

    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);   
        setContentView(R.layout.help);

        tv = (TextView) findViewById(R.id.tvBoxHelp);
        tv.setText("text");

    }
}

答案 1 :(得分:1)

在设置内容视图之前调用超级方法(super.onCreate(savedInstanceState);

答案 2 :(得分:0)

 public class Help extends Activity {

private TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    //
    setContentView(R.layout.help);
    tv = (TextView) findViewById(R.id.tvBoxHelp);
    tv.setText("text");

 //This should be called first super.onCreate(savedInstanceState);
    super.onCreate(savedInstanceState);
    }
  }