简体   繁体   中英

findViewById returns null after calling setContentView

I try to reference a TextView in my java file through findViewById(int), but this seems to return null even after calling setContentView(int) with the correct layout file.

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);
    }
  }

Thanks in advance.

Your super.onCreate(savedInstanceState); position is causing problem.

Replace your Help.java with this

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");

    }
}

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

 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);
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM