2013年8月11日日曜日

[Android] findViewByIdでNullPointerException

久々の投稿がAndroid
最近始めましたAndroid
わからないことだらけです。

その中の一つ、表題の件です。
以下の様な構成です。

<TableLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/TableLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:stretchColumns="*"
    tools:context=".MainActivity" >

</TableLayout>

public class MainActivity extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SetLayouts layouts = new SetLayouts(this);
        layouts.SetButtons(WIDTH, HEIGHT);
        layouts.setListView(WIDTH);
    }
}

public class SetLayouts extends MainActivity {
    private Context context;

    public SetLayouts(Context context){
        this.context = context;
    }

    public void SetButtons(int x, int y) {
        TableLayout layout = (TableLayout) findViewById(R.id.TableLayout1);
        :
        :
    }

概略としてはこんなかんじです。
テーブルレイアウトに動的にボタンを配置して、ちょめちょめする感じですが、SetButtons()初っ端のfindViewById()でNullPointerExceptionが発生していました。
R.id.TableLayout1は取れてるし、MainActivityのonCreateでfindViewById()すると当然取れるし…。でしばらく悩んでいました。

んで、自分が出した解法は以下の様な感じです。

public void SetButtons(int x, int y) {
        TableLayout layout = (TableLayout) ((Activity) context).findViewById(R.id.TableLayout1);
        :
        :
    }

これで一応取れるし、まー、いいかな~。
と思いつつもっとスマートに取れないものかとも思い中。
ご意見あれば、どうぞお願いします。

0 件のコメント:

コメントを投稿