【问题标题】:Android App crashing at beginningAndroid App 一开始就崩溃
【发布时间】:2013-11-13 17:53:59
【问题描述】:

我正在学习 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 新代码(并保持默认),应用程序可以工作,但每当我声明其中一个变量时它就不会。

感谢您的宝贵时间。非常感谢。任何帮助都会很棒。

【问题讨论】:

  • 在初始化Button和TextView之前移动setContentView(R.layout.activity_main);行

标签: java android xml android-activity main


【解决方案1】:

你应该在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);

【讨论】:

  • 非常感谢。但是在我正在跟随讲师的教程中,代码是这样的,那么为什么它需要有所不同呢?非常感谢您的回答
  • 操作!那是我的错。我纠正了代码,你是完全正确的。那是我不会再犯的错误。谢谢!
猜你喜欢
  • 2018-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-24
  • 2019-10-05
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多