Android findViewById()有问题。。。当我不使用'时返回NULL;我不认为应该

Android findViewById()有问题。。。当我不使用'时返回NULL;我不认为应该,android,Android,这是一个Android资源文件: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="fill_parent" android:layout_width="fill_parent" android:paddingLeft="20dip" an

这是一个Android资源文件:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="fill_parent" 
    android:layout_width="fill_parent"
android:paddingLeft="20dip"
android:paddingRight="20dip" android:orientation="vertical">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="left"
        android:id="@+id/pt_name_view"/>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="left"
    android:id="@+id/pt_dob_view"/>

   <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="left"
    android:id="@+id/pt_mrun_view"/>

</LinearLayout> 

直到最近,这段代码还运行得很好。现在,当代码运行时,尽管两个文件都没有被更改,但nameView突然变为NULL。

每当您对资源进行一点更改(甚至添加空格、字符、移动文件、添加文件……),您的项目编译有时可能会出错


只要记住,没有什么是完美的,并有一个良好的做法。您已经学到了一个教训:
在运行之前始终保存并清理项目

我清理了项目,问题就消失了。不过,我还是不知道为什么会发生这种情况。我敢打赌,如果您使用的是Eclipse,它有时会扰乱资源编译。当你看到奇怪的事情发生时,首先尝试清理项目。或者你可以切换到Intellij IDEA,它根本没有这样的问题。
public class PatientViewActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    setContentView(R.layout.patient_view);

        // ... some irrelevant code ... 

        final TextView nameView = (TextView) findViewById(R.id.pt_name_view);
        nameView.setText(pt.getSurname().toUpperCase() + ", " + pt.getGivenNames() );

        // ... some more irrelevant code ...

}