2011年7月24日日曜日

findViewByIdでnullが返る

開発環境:
Windows Vista Home
eclipse 3.5(ガリレオ)
ADT_今日の時点で最新の物(バージョン不明)
JavaSDK 1.6.0_24
AndroidSDK_r11
開発・ターゲットVer=Android2.1


テスト環境:
媒体 = エミュレータ
↑SDK ManagerでVer2.1のHVGAで作成


nullが返るソース。

・aaa.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:id="@+id/linLay"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
    </LinearLayout>
</LinearLayout>


・bbb.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TableLayout
        android:id="@+id/tblLay" 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
    </TableLayout>
</LinearLayout>


MainActivity.java(修正前)
public class MainActivity extends Activity{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.aaa); ← ここに注目(aaa.xmlを設定)
 
        // 正常な値が返ってくる(aaa.xml内のidから取得)
        LinearLayout LinLay = (LinearLayout)findViewById(R.id.linLay);
        // nullが返ってくる(bbb.xml内のidから取得)
        TableLayout TabLay = (TableLayout)findViewById(R.id.tblLay);
    }
}


自分自身のレイアウトは「aaa.xml」になっている。

setContentView(R.layout.aaa);
これで決定する。

findViewByIdで現在設定されていない他のレイアウトからオブジェクトを取得しようとしても、普通に取得しようとしてもnullが返ってくる。

いくつか方法があるが、今回は「LayoutInflater」を使う。


MainActivity.java(修正後)
public class MainActivity extends Activity{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.aaa); ← ここに注目(aaa.xmlを設定)

        // 正常な値が返ってくる(aaa.xml内のidから取得)
        LinearLayout LinLay = (LinearLayout)findViewById(R.id.linLay);

        // レイアウトインフレーター使用
        LayoutInflater factory = LayoutInflater.from(this);
        // 他のレイアウトファイルを指定
        View layInfView = factory.inflate(R.layout.bbb, null);

        // 正常な値が返ってくる(bbb.xml内のidから取得)
        TableLayout TabLay = (TableLayout)layInfView.findViewById(R.id.tblLay);
    }
}

   ↓クリックで、このブログの評価が上がり執筆者が喜びます
にほんブログ村 IT技術ブログ プログラム・プログラマーへ
   にほんブログ村

0 件のコメント: