0

何かを試すために、ビューの背景を赤に設定しようとしています。アクティビティレイアウトにビューを追加し、ID「gradientView」を付けました。私のJavaコードでは、次のような新しいビューを作成します。

    View gradientView = (View) findViewById(R.id.gradientView);

そしてonCreateで私はこれを行います:

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_clean_weather);
    gradientView.setBackgroundColor(Color.RED);

何らかの理由で、findViewByIdでNullPointerExceptionが発生します。XMLのビューを参照したときに、「nullではない」と思ったのですか?!

誰かが何が起こっているのか知っていますか?

ありがとう。

4

1 に答える 1

3

あなたfindviewByIdは後に来るべきsetContentView(..)です;

例:

 super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_clean_weather);
    View gradientView = (View) findViewById(R.id.gradientView);
    gradientView.setBackgroundColor(Color.RED);

それ以外の場合gradientViewはnullになり、null参照に対する操作はすべて。になりNullPointerExceptionます。

于 2012-10-03T20:59:18.210 に答える