1

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 が返され、その理由もわかりません。このコードはとてもシンプルです。

4

2 に答える 2

6
text.setText(10);

このようにして を探しています にString変更id = 10;する必要があります

 text.setText(String.valueOf(10));
于 2013-05-14T11:57:17.683 に答える
0

このコードを使用する.......

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;
    }
}
于 2013-05-14T12:02:09.513 に答える