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)”,它运行正常,为什么?
答案 0 :(得分:3)
应该在setAdapter之前调用addHeaderView。否则,您将收到IllegalStateException。
您的新代码应为:
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");