我是新來的Android編程和下面的程序是我的第一個Android應用
我.java
文件爲什麼我的Android應用程序意外停止?
public class MainActivity extends Activity
{
Button btn = (Button) findViewById(R.id.btn);
private OnClickListener btn_click = new OnClickListener() {
public void onClick(View v) {
btn.setText("Hi there!");
}
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
btn.setOnClickListener(btn_click);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
我.XML
文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My Button" />
</RelativeLayout>
我想一旦我點擊按鈕My Button
它的文本改變「你好!」。但是,當我的應用程序正在在模擬器中運行,它打破並彈出一條消息:
的應用testapp_1(過程com.example.testapp_1)意外
什麼是我的錯誤採空?以及我如何解決它們?
'Button btn =(Button)findViewById(R.id.btn);'您還需要將其移入方法中。所有Java可執行代碼都必須存在於方法中。大概把它放在'onCreate'上,這取決於你想要的可見性。 – Simon