为什么findViewById()会引发空异常? ?
为什么findViewById抛出空异常这里是布局和源代码文件:为什么findViewById()会引发空异常? ?
<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,我不知道甚至为什么。该守则非常简单。
text.setText(10);
这样
你正在寻找一个id = 10;
你String
应该
text.setText(String.valueOf(10));
这是正确的! – huaxz1986 2013-05-14 12:03:03
使用更改此代码................
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;
}
}
问题是:setText(10)不正确,它必须是setText(String)。所以当我将它改为setText(10+“”)时,它的工作原理是正确的。 – huaxz1986 2013-05-14 12:05:19
好的享受......... – 2013-05-14 12:07:35
does usernameText属于activity_main? – Blackbelt 2013-05-14 11:56:00
@ huaxz1986 text.setText(10 +“”);和TextView text =(TextView)findViewById(R.id.usernameText); – TheFlash 2013-05-14 11:56:20
尝试callinng'findViewById(R.id.usernameText)''不带MainActivity.this – Wamasa 2013-05-14 11:57:14