我真的不明白为什么这个简单的代码会在这一行崩溃layout.addView(button);
super.onCreate(savedInstanceState);
layout = (LinearLayout)findViewById(R.id.linearLayout);
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
Button button = new Button(this);
button.setHeight(100);
button.setWidth(100);
button.setText("HELLO");
button.setLayoutParams(p);
layout.addView(button);
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/linearLayout">
</LinearLayout>
编辑:编辑后的代码仍然崩溃。但现在在 setContentView 中崩溃了。
super.onCreate(savedInstanceState);
layout = (LinearLayout)findViewById(R.id.linearLayout);
setContentView(layout);
LayoutParams p = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
int i,j;
Button button = new Button(this);
button.setHeight(100);
button.setWidth(100);
button.setText("HELLO");
layout.addView(button,p);
Logcat 报告