1

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

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

模拟器错误 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;
     }

    }
}
4

3 回答 3

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);
    }
于 2012-11-06T17:02:29.590 回答
1

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

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);
}
于 2012-11-06T17:04:07.053 回答
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);
    }
于 2012-11-06T17:02:59.323 回答