簡體   English   中英

為什么findViewById()拋出Null異常?

[英]Why findViewById() throws Null Exception?

為什么findViewById會引發NULL異常?這是布局和源代碼文件:

<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 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;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM