我的简单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" />
问题是什么? 感谢。