我的简单 Android 代码有问题;我想做一个简单的活动,其中有一个调用方法的按钮;我想通过它的“id”(button1) 将该按钮链接到在activity_main.xml 中定义的按钮。但是
当我启动它时,我没有问题:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = new Button(this);
button.setText("Clicca qui");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSecondActivity();//method implemented by myself.
}
});
setContentView(button);
}
当我启动它时,它崩溃了:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button1);//it calls a button defined in xml
button.setText("Clicca qui");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startSecondActivity();//method implemented by myself.
}
});
setContentView(button);
}
activity_main.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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="27dp"
android:text="Button" />
哪个是问题?谢谢。