为什么在listview中添加标题视图会导致应用程序崩溃?

时间:2011-09-15 05:49:43

标签: android android-layout

    super.onCreate(savedInstanceState);
    ListView lv = new ListView(this);
    String[] meals = getResources().getStringArray(R.array.meals);
    lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item,
            meals));
    lv.setTextFilterEnabled(true);
    college = getIntent().getExtras().getString("COLLEGE");
    setTitle(college);
    TextView t = new TextView(this);
    t.setText("asdfadsfdfsa");
    lv.addHeaderView(t);
    setContentView(lv);

运行此命令会导致程序崩溃。如果我拿出“lv.addHeaderView(t)”,它运行正常,为什么?

2 个答案:

答案 0 :(得分:3)

应该在setAdapter之前调用addHeaderView。否则,您将收到IllegalStateException。

参考http://developer.android.com/reference/android/widget/ListView.html#addHeaderView%28android.view.View%29

您的新代码应为:

  

super.onCreate(savedInstanceState);
ListView lv = new ListView(this);
String[] meals = getResources().getStringArray(R.array.meals);
TextView t = new TextView(this);
t.setText("asdfadsfdfsa");
lv.addHeaderView(t);
lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, meals));
lv.setTextFilterEnabled(true);
college = getIntent().getExtras().getString("COLLEGE");
setTitle(college);
setContentView(lv);

答案 1 :(得分:0)

我认为那是因为你的textview维度没有设置。 尝试这样做

TextView t = new TextView(this);
t.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,
                                             LayoutParams.FILL_PARENT));
t.setText("asdfadsfdfsa");