我学习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新代码(并保持默认状态),该应用程序可以正常工作,但不会在我声明其中一个变量时使用。
我很感激你的时间。非常感谢你。任何帮助都会很棒。
移动'的setContentView(R.layout.activity_main)后,您应该初始化视图;'初始化按钮和TextView中前行 –