hua*_*986 1 android findviewbyid
为什么findViewById抛出NULL异常?这是布局和源代码文件:
<RelativeLayout
...
tools:context=".MainActivity" >
<TextView
android:id="@+id/usernameText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)
这是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
}
}
Run Code Online (Sandbox Code Playgroud)
但是,findViewById()返回null,我甚至不知道为什么.本规范非常简单.
text.setText(10);
Run Code Online (Sandbox Code Playgroud)
这样你正在寻找一个String与id = 10;你应该改变
text.setText(String.valueOf(10));
Run Code Online (Sandbox Code Playgroud)