findViewById が NULL 例外をスローするのはなぜですか?レイアウトとソースコード ファイルは次のとおりです。
<RelativeLayout
...
tools:context=".MainActivity" >
<TextView
android:id="@+id/usernameText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
MainActivity のソース コードは次のとおりです。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try{
TextView text=(TextView)MainActivity.this.findViewById(R.id.usernameText);
text.setText(10);
}catch(Exception e){
Log.i("Log", e.getMessage()+"Error!"); // LogCat message
}
}
しかし、findViewById()
null が返され、その理由もわかりません。このコードはとてもシンプルです。