-2

私はAndroidが初めてです。ボタン付きの EditText に応じて TextView を変更する簡単なコードを書いています。コードにエラーはありません。しかし、デバイスから実行すると強制終了します。

これが私のコードです:

public class MainActivity extends Activity {

    //EditText et = (EditText)findViewById(R.id.editText1); << Error if uncomment
    //TextView tv = (TextView)findViewById(R.id.textView1); << Error if uncomment

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}
4

3 に答える 3

2

findViewById()クラス変数をその場で初期化するために使用することはできません

public class MainActivity extends Activity {

    EditText  et;
    TextView  tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // move these here
        et = (EditText)findViewById(R.id.editText1);
        tv = (TextView)findViewById(R.id.textView1);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

考えてみると、レイアウトは呼び出しの後にのみ初期化されるsetContentViewため、初期化される前、またはアクティビティのレイアウトとして設定される前に、そのレイアウト内の要素を見つけることはできません。

于 2013-03-10T20:17:20.637 に答える
0

常にコンテンツを確認し、質問とともに投稿してくださいLogCat

これを試して:

public class MainActivity extends Activity {

    // You can use findViewById only once the activity has finished creating, so move the initialization to onCreate function
    EditText  et;
    TextView  tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et = (EditText)findViewById(R.id.editText1);
        tv = (TextView)findViewById(R.id.textView1);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

編集:

次のようなものを開くことができますLogCat:円でマークされたボタンをクリックします(Eclipseの右下にあります)

ここに画像の説明を入力

そこにない場合は、次のように表示できます。

ここに画像の説明を入力

PS: 私は mac を使用していますが、他の OS でも同じはずです。

于 2013-03-10T20:20:43.260 に答える
-1

1 つのことを心に留めておいてください。findViewById呼び出した後は 常に呼び出してくださいsetContent。そうしないと、このようなエラーが発生します。

于 2013-03-10T20:35:08.173 に答える