初歩的なところでハマる
おもむろにAndroidプログラム作成中にハマった事。
とりあえずHelloWorldなプロジェクトから、Buttonをxmlでレイアウトに記述した。idも設定して、
ソースコードからuttonを取得した。
↓こんな感じで
Button btn = (Button)findViewById(R.id.button);
btn.setText("hoge_button");
そしたら、何故か落ちるプログラム。
↓が今回のレイアウト。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center"> <TextView android:text="@string/hello_world" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:text="button" android:layout_height="wrap_content" android:layout_width="wrap_content" id="@+id/button"/> </LinearLayout>
最初何がおかしいのか分からなかった…
しかし、よーく見るとIDの設定が
<Button android:text="button" android:layout_height="wrap_content" android:layout_width="wrap_content" id="@+id/button"/>
android: が抜けてた為にIDが空だったため、
そもそもfindViewById()出来てなかったという。
っていうか、こんな記述通るんだね…勉強になった。