我的Android应用程序因未知原因而崩溃。这是代码:
public class MainActivity extends ActionBarActivity {
EditText x1 = (EditText)findViewById(R.id.idEdittext);
TextView x2 = (TextView)findViewById(R.id.idtext);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(this, "Welcome", Toast.LENGTH_LONG).show();
}
启动方法
@Override
protected void onStart() {
super.onStart();
Toast.makeText(this, "This is your first App :)) ", Toast.LENGTH_LONG).show();
}
这是单击按钮时执行按钮的方法
public void onClick() {
String name = String.valueOf(x1.getText());
Toast.makeText(this," Welcome " + name +"" +"to Android" , Toast.LENGTH_LONG).show();
x2.setVisibility(View.INVISIBLE);
}
当我运行它时,它崩溃了说"不幸的是,你的应用程序停止了#34;
答案 0 :(得分:4)
在创建活动之前,不应致电findViewById
。
更改您的代码:
public class MainActivity extends ActionBarActivity {
EditText x1;
TextView x2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
x1 = (EditText)findViewById(R.id.idEdittext);
x2 = (TextView)findViewById(R.id.idtext);
Toast.makeText(this, "Welcome", Toast.LENGTH_LONG).show();
}