こものAndroidメモ

Androidアプリの開発メモブログ!!

カスタムViewでヌルポ —

[問題]

カスタムViewにおいて、findViewByIdでnullが返ってくる

[症状]

Viewクラスを継承して、自分の使いやすいカスタムViewを作りました。

public class CustomView extends View {
    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
}

レイアウト用のxmlに配置して、画面上では自由に描画できるのですが、

CustomView cview = (CustomView) findViewById(R.id.idTestCustomView);

とすると、nullが返ってきます。

[原因]

コンストラクタが、

public CustomView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

だけではなく、

public CustomView(Context context) {
    super(context);
}

も必要。

これでfindViewByIdに成功しました。



Categorised as: View関連



コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です