0

Android 開発について学んでいるのですが、なぜアプリがクラッシュするのか疑問に思っています

メインコード:

package com.tester.myapp;

import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
import android.view.Menu;
import android.view.View;

public class Main extends Activity {

    Button carrega;
    TextView texto;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        carrega = (Button)findViewById(R.id.carregar);
        texto = (TextView)findViewById(R.id.textView3);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        carrega.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                texto.setText("newtext");
            }
        });
    }

    @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;
    }

}

そして私のXMLは次のとおりです。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >

    <TextView
        android:id="@+id/textView3"
        android:layout_width="fill_parent"
        android:layout_height="35dp"
        android:background="#A5BB76"
        android:text="@string/message" />
    <Button
        android:id="@+id/carregar"
        android:layout_width="fill_parent"
        android:layout_height="50dp"
        android:text="@string/OK"
    />

</LinearLayout>

このアプリは XML だけで問題なく動作しますが、それらの変数 (Button と TextView) を定義すると、開始時にクラッシュします。なぜこうなった?どうすればこれを解決できますか? Java の新しいコードを削除 (およびデフォルトを維持) すると、アプリは機能しますが、これらの変数のいずれかを宣言するたびに機能しません。

お時間をいただきありがとうございます。どうもありがとうございました。どんな助けでも素晴らしいでしょう。

4

1 に答える 1

4

の後にビューを初期化する必要があります setContentView(R.layout.activity_main);

それを変更

@Override
    protected void onCreate(Bundle savedInstanceState) {
        carrega = (Button)findViewById(R.id.carregar);
        texto = (TextView)findViewById(R.id.textView3);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        carrega = (Button)findViewById(R.id.carregar);
        texto = (TextView)findViewById(R.id.textView3);
于 2013-11-02T18:26:27.437 に答える