为什么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,我不知道甚至为什么。该守则非常简单。

+0

does usernameText属于activity_main? – Blackbelt 2013-05-14 11:56:00

+0

@ huaxz1986 text.setText(10 +“”);和TextView text =(TextView)findViewById(R.id.usernameText); – TheFlash 2013-05-14 11:56:20

+0

尝试callinng'findViewById(R.id.usernameText)''不带MainActivity.this – Wamasa 2013-05-14 11:57:14

text.setText(10); 
这样

你正在寻找一个id = 10;String应该

text.setText(String.valueOf(10)); 
+1

这是正确的! – 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; 
    } 
} 
+0

问题是:setText(10)不正确,它必须是setText(String)。所以当我将它改为setText(10+“”)时,它的工作原理是正确的。 – huaxz1986 2013-05-14 12:05:19

+0

好的享受......... – 2013-05-14 12:07:35