我的Android-Emulator显示模拟器错误

时间:2012-11-06 17:00:18

标签: java android

我制作了一个Android应用程序。 Eclipse没有报告我的代码中有哪些错误。

但如果我运行我的项目,那么模拟器会显示:

emulator error http://s2.ipicture.ru/uploads/20121106/466GCZH9.png

我的Java代码是(MainActivity.java):

package ru.startandroid.develop.AppLog;

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

public class MainActivity extends Activity implements OnClickListener{
    TextView myText = (TextView) findViewById(R.id.myText);
    Button myBtnCancel = (Button) findViewById(R.id.myBtnCancel);
    Button myBtnOK = (Button) findViewById(R.id.myBtnOK);

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.myBtnCancel: 
            myText.setText("Нажата кнопка Cancel"); 
        break;
        case R.id.myBtnOK: 
            myText.setText("Нажата кнопка ОК"); 
        break;
     }

    }
}

3 个答案:

答案 0 :(得分:2)

您只能在致电findViewById()后使用setContentView()

public class MainActivity extends Activity implements OnClickListener{
    TextView myText;
    Button myBtnCancel;
    Button myBtnOK;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        myText = (TextView) findViewById(R.id.myText);
        myBtnCancel = (Button) findViewById(R.id.myBtnCancel);
        myBtnOK = (Button) findViewById(R.id.myBtnOK);
    }

答案 1 :(得分:1)

您需要在findById方法之后绑定调用setContentView的小部件(TextView和Buttons),因为它取决于它:

TextView myText;
Button myBtnCancel;
Button myBtnOK;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    myText = (TextView) findViewById(R.id.myText);
    myBtnCancel = (Button) findViewById(R.id.myBtnCancel);
    myBtnOK = (Button) findViewById(R.id.myBtnOK);
}

答案 2 :(得分:0)

更改您的代码,如下所示:

在实例级别声明变量并在onCreate()

中分配值
public class MainActivity extends Activity implements OnClickListener{
    TextView myText = null;
    Button myBtnCancel = null;
    Button myBtnOK = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        myText = (TextView) findViewById(R.id.myText);
        myBtnCancel = (Button) findViewById(R.id.myBtnCancel);
        myBtnOK = (Button) findViewById(R.id.myBtnOK);
    }