When I try to run the following code I get an error. The emulator gives me this error message and then the app force closes: The application has stopped unexpectedly. What is wrong?
import edu.chl.dat255.bluebanana.R;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Linear开发者_运维技巧Layout;
import android.widget.TextView;
public class ProMan extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout layout = (LinearLayout) findViewById(R.layout.main);
TextView t = new TextView(getApplicationContext());
t.setText("Hello world");
layout.addView(t);
}
}
LinearLayout layout = (LinearLayout) findViewById(R.id.mainLayout);
In your xml file main xml layout android:id="@+id/mainLayout"
You should set id for your root LinearLayout in main.xml like
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/mainLayout">
and then reference it as
LinearLayout layout = (LinearLayout) findViewById(R.id.mainLayout);
instead of findViewById(R.layout.main);
You should provide layout information on `TextView t . layout width and layout height should be provided. See code below.
LinearLayout.LayoutParams params =
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, 0.0F);
t.setLayoutParams(tvParams);
layout.addView(t);
精彩评论