Android:Layout.addView()不起作用

时间:2011-09-16 13:40:41

标签: android layout view emulation

当我尝试运行以下代码时,出现错误。模拟器给我这个错误消息,然后app force关闭: 应用程序意外停止。有什么问题?

import edu.chl.dat255.bluebanana.R;
import android.app.Activity;
import android.os.Bundle;
import android.widget.LinearLayout;
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);
    }
}

3 个答案:

答案 0 :(得分:7)

  LinearLayout layout = (LinearLayout) findViewById(R.id.mainLayout);

In your xml file main xml layout android:id="@+id/mainLayout" 

答案 1 :(得分:2)

您应该在main.xml中为根LinearLayout设置id,如

<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">

然后将其引用为

LinearLayout layout = (LinearLayout) findViewById(R.id.mainLayout);

而不是findViewById(R.layout.main);

答案 2 :(得分:0)

您应该在`TextView t上提供布局信息。应提供布局宽度和布局高度。请参阅下面的代码。

LinearLayout.LayoutParams params = 
    new LinearLayout.LayoutParams( 
       ViewGroup.LayoutParams.WRAP_CONTENT, 
       ViewGroup.LayoutParams.WRAP_CONTENT, 0.0F);
t.setLayoutParams(tvParams);

layout.addView(t);