2013-11-02 140 views
0

我学习Android开发,我想知道为什么我的应用程序崩溃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新代码(并保持默认状态),该应用程序可以正常工作,但不会在我声明其中一个变量时使用。

我很感激你的时间。非常感谢你。任何帮助都会很棒。

+3

移动'的setContentView(R.layout.activity_main)后,您应该初始化视图;'初始化按钮和TextView中前行 –

回答

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); 
+0

非常感谢。但是在教程中,我遵循教练的做法,那么为什么它需要不同?非常感谢您的回答。 –

+0

如果它按照您所示的方式进行,那就错了。 – Simon

+0

ops!那是我的错。我纠正了代码,你完全正确。这是我没有再犯的错误。谢谢! –