Android 为什么findViewById()抛出Null异常?
为什么findViewById引发空异常?以下是布局和源代码文件:Android 为什么findViewById()抛出Null异常?,android,findviewbyid,Android,Findviewbyid,为什么findViewById引发空异常?以下是布局和源代码文件: <RelativeLayout ... tools:context=".MainActivity" > <TextView android:id="@+id/usernameText" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </RelativeLayout&
<RelativeLayout
...
tools:context=".MainActivity" >
<TextView
android:id="@+id/usernameText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
然而,findViewById()
返回null,我甚至不知道为什么。这段代码非常简单
text.setText(10);
通过这种方式,您正在查找id为10的字符串
代码>您应该在中更改
text.setText(String.valueOf(10));
通过这种方式,您正在查找id为10的字符串
代码>您应该在中更改
text.setText(String.valueOf(10));
使用此代码
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;
}
}
使用此代码
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;
}
}
usernameText是否属于活动_main?@huaxz1986 text.setText(10+“”);和TextView text=(TextView)findViewById(R.id.usernameText);尝试在不使用main活动的情况下调用findViewById(R.id.usernameText)。this@blackbelt:它属于活动_main。标题为“抛出空异常”,题体为“返回空”,接受的答案表示根本没有空。即使你已经解决了你的问题,这也不太可能以目前的形式帮助任何人。投票以“太本地化”结束。usernameText是否属于活动_main?@huaxz1986 text.setText(10+);和TextView text=(TextView)findViewById(R.id.usernameText);尝试在不使用main活动的情况下调用findViewById(R.id.usernameText)。this@blackbelt:它属于活动_main。标题为“抛出空异常”,题体为“返回空”,接受的答案表示根本没有空。即使你已经解决了你的问题,这也不太可能以目前的形式帮助任何人。投票以“太本地化”结束。问题是:setText(10)不正确,它必须是setText(String)。因此,当我将其更改为setText(10+“”)时,它工作正常。问题是:setText(10)不正确,它必须是setText(String)。因此,当我将其更改为setText(10+“”)时,它工作正常。