加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Android;在类体中声明edittext(在任何方法中)

发布时间:2020-12-15 08:47:16 所属栏目:Java 来源:网络整理
导读:我有编程语言的经验,但对于 android编程有点新. 我有一个程序,其中包含一些字段,用作标签(textview),按钮和数据输入(edittext). 每当我在程序开头用任何方法声明它们时(当然在课堂上),当我启动我的应用程序时它崩溃并且模拟给出“不幸的是,你的程序已经停止
我有编程语言的经验,但对于 android编程有点新.

我有一个程序,其中包含一些字段,用作标签(textview),按钮和数据输入(edittext).

每当我在程序开头用任何方法声明它们时(当然在课堂上),当我启动我的应用程序时它崩溃并且模拟给出“不幸的是,你的程序已经停止”警报.

Eclipse没有给出声明的任何错误,我确实使用相同的方式来定义没有问题的常规变量.当我在类体中声明一个mediaplayer对象时,它也会出现相同的错误.

有谁知道它为什么会出错?
是否有另一种方式来声明全局对象,如edittext,viewtext等…在方法中一遍又一遍地声明它们对我来说听起来很奇怪.

谢谢!!

公共类TrainerActivity扩展Activity {

Button stopTimer = (Button)findViewById(R.id.StopTimer);
Button startTimer = (Button)findViewById(R.id.StartTimer);
EditText totalTime = (EditText)findViewById(R.id.TotalTime);
EditText enterMin = (EditText)findViewById(R.id.EnterMin);
EditText enterSec = (EditText)findViewById(R.id.EnterSec);

private boolean breaker = false;

@Override

public void onCreate(Bundle savedInstanceState)
{

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


    startTimer.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            Button_StartTimer();
        }
    });

    stopTimer.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            Button_StopTimer();
        }
    });
}

解决方法

如果没有看到你正在尝试的代码的示例代码,就不可能明确地说(我们不会在这里做读心).但是让我猜一下,你在做这样的事情?……

public class MyActivity extends Activity {

    TextView tv1; // This is fine.
  ? TextView tv2 = (TextView) findViewById(R.id.textview2); // Don't do this.

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

        tv1 = (TextView) findViewById(R.id.textview1); // This is fine
        tv1.setText("Some text"); // This works

        tv2.setText("Some text"); // NullPointerException here

    }
}

tv2.setText(…)将失败,因为您在调用setContenetView(…)之前使用了findViewById(…),因此,tv2将为null.

将您的小部件声明为Activity中的实例成员,但在设置内容视图之后不要尝试使用findViewById(…),这是完全可以接受的.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读