[英]Why findViewById() throws Null Exception?
Why findViewById throws NULL Exception?Here is layout and sourcecode file: 为什么findViewById会引发NULL异常?这是布局和源代码文件:
<RelativeLayout
...
tools:context=".MainActivity" >
<TextView
android:id="@+id/usernameText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
And here is the source code in MainActivity: 这是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
}
}
However, findViewById()
returns null, and I don't know even why. 但是,
findViewById()
返回null,我也不知道为什么。 This Code is so simple. 该代码是如此简单。
text.setText(10);
in this way you are looking for a String
with id = 10;
这样,您正在寻找
id = 10;
的String
id = 10;
You should change in 你应该改变
text.setText(String.valueOf(10));
use this code................ 使用此代码...
public class MainActivity extends Activity {
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text =(TextView)findViewById(R.id.usernameText);
try{
text.setText(String.valueOf(10));
}catch(Exception e){
Log.i("Log", e.getMessage()+"Error!"); // LogCat message
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.