【发布时间】:2009-10-13 11:12:35
【问题描述】:
我最近开始使用 android。
这段代码我已经写好了
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ArrangeMe extends Activity {
private Button button1;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.button1 = (Button)findViewById(R.id.buttonOne);
this.button1.setOnClickListener(new OnClickListener() {
//@Override
public void onClick(View v) {
finish();
}
});
setContentView(R.layout.main);
}
}
我的 main.xml 如下所示
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="ArrangeMe"/>
<Button android:text="Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/buttonOne"></Button>
</LinearLayout>
但是当我通过这条线时
this.button1 = (Button)findViewById(R.id.buttonOne);
我观察到 button1 = null。但是当我输入 R.id 时。 eclipse 确实建议了一个自动完成 buttonOne(这表明布局 xml 是正确的!)
我哪里错了?
编辑:
有趣的是,我尝试了以下代码,
按钮仍然没有出现。它已经停止崩溃,但按钮没有出现!
button1 = new Button(getContext());
button1.setText("1");
addView(button1, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
button1.setOnClickListener(new OnClickListener() {
//@Override
public void onClick(View v) {
finish();
}
});
这是报错
我把它们改成
button1 = new Button(getBaseContext());
button1.setText("1");
addContentView(button1, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
button1.setOnClickListener(new OnClickListener() {
//@Override
public void onClick(View v) {
finish();
}
});
【问题讨论】: