我在调用ListView的ListView.getChildAt()
之后尝试运行setAdapter()
方法,但它给了我NullPointerException
。似乎设置适配器不会导致创建子视图。如下面的方法所示,我正在尝试获取子视图,以便我可以更改其背景颜色。我该如何解决这个问题?
private void showAnswers(int questionLocation)
{
List<Answer> answers = getAnswersByQuestionLocation(questionLocation);
ArrayAdapter<String> answerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_activated_1);
for (int i = 0; i < answers.size(); i++)
{
answerAdapter.add(mOptionLetters[i] +". "+ answers.get(i).getAnswerText());
}
mAnswerList.setAdapter(answerAdapter);
if (mAnswerLocationByQuestionLocation.indexOfKey(questionLocation) > -1)
{
Log.v("Child Count",String.valueOf(mAnswerList.getChildCount()));
//mAnswerList.getChildAt(
// mAnswerLocationByQuestionLocation.get(questionLocation))
// .setSelected(true);
}
}
答案 0 :(得分:3)
如果您只需更改背景, 这是怎么回事:
ArrayAdapter<String> answerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_activated_1) {
@Override
public View getView(int position, View convertView,
ViewGroup parent) {
View v =super.getView(position, convertView, parent);;
v.setBackgroundColor(Color.RED);
return v;
}
};
因为您在UI线程上运行,所以listView将需要足够的时间在线程的下一个循环中创建视图,但您无法猜测何时。
所以最好的方法是覆盖适配器中的getView
,因为适配器将listView与子节点一起提供:)
class MyModel {
public MyMode(String txt){
this.txt = txt
}
public String txt;
public boolean isSelected;
@Override
public String toString() {
return txt;
}
}
ArrayAdapter<MyModel> answerAdapter = new ArrayAdapter<MyModel>(this,
android.R.layout.simple_list_item_activated_1) {
@Override
public View getView(int position, View convertView,
ViewGroup parent) {
View v =super.getView(position, convertView, parent);;
MyModel model = getItem(position);
if(model.isSelected){
v.setBackgroundColor(Color.RED);}
else{
v.setBackgroundColor(Color.WHITE);}
return v;
}
};
answerAdapter.add(new MyModel(mOptionLetters[i] +". "+ answers.get(i).getAnswerText()));
if (mAnswerLocationByQuestionLocation.indexOfKey(questionLocation) > -1)
{
MyModel model = (MyModel)mAnswerList.getItemAtPosition(questionLocation);
model.isSelected= true;
answerAdapter.notifyDataSetChanged();
}
}
无论如何,您需要阅读有关ListViews和Adapters的本教程 http://www.vogella.com/articles/AndroidListView/article.html