我有一个ListView
包含有关广播电台的信息。它由多个自定义项(TextView
+ CheckBox
)和嵌入式AutoCompleteTextView
组成。我的问题是我实现了ListView's
Adapter
的getView()方法可能不正确,因为只有当我不选择AutoCompleteTextView
时它才会向上和向下滚动,因为在我执行该操作之后空指针异常。更清楚的是,这是我的自定义适配器代码的片段:
class ImageAdapter extends ArrayAdapter<RadioStations> {
private Activity a;
private LayoutInflater inflater;
private View searchView;
private ArrayAdapter<RadioStation> mAdapter;
public ImageAdapter(Activity act, RadioStation[] objects) {
super(act, 0, objects);
a = act;
inflater = (LayoutInflater) a.getSystemService(LAYOUT_INFLATER_SERVICE);
mAdapter = new ArrayAdapter<RadioStation>(RadioStationListActivity.this, android.R.layout.simple_dropdown_item_1line, mStations);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.i(TAG, "GETTING VIEW[" + position + "]");
final TextView NameOfStation;
CheckBox FavouriteFlag;
if(position == 0) {
Log.d(TAG, "Making AutoCompleteTextView");
searchView = inflater.inflate(R.layout.search_view, null);
((AutoCompleteTextView)searchView.findViewById(R.id.Seacrh_field)).setAdapter(mAdapter);
((AutoCompleteTextView)searchView.findViewById(R.id.Seacrh_field)).setOnItemClickListener(
new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
...
}
}
);
searchView.setFocusable(true);
return searchView;
}
if(convertView == null || convertView == searchView){
Log.w(TAG, "Convert view is null");
convertView = inflater.inflate(R.layout.radio_list_item, null);
}
final RadioStation station = getItem(position-1);
NameOfStation = (TextView) convertView.findViewById(R.id.name_of_chanel);
FavouriteFlag = (CheckBox) convertView.findViewById(R.id.favorite);
if(NameOfStation == null)
Log.d(TAG, "Name of station is null!!!!!!!!!");
NameOfStation.setText(station.toString());
FavouriteFlag.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
...
}
});
FavouriteFlag.setFocusable(false);
return convertView;
}
}
所以,如果有人看到我的错误,我会很乐意接受你的建议。顺便说一句,当我尝试将文本放入NameOfStation
时,我得到NullPointerException,因为尽管条件允许,但仍然是convertView仍然是搜索视图
if(convertView == null || convertView == searchView)
convertView = inflater.inflate(R.layout.radio_list_item, null);
答案 0 :(得分:3)
如果搜索视图应该是列表的一部分并且还应该使用它滚动,则可以使用ListView类的addHeaderView()来设置它,以将视图添加到列表的顶部,该视图不由适配器管理。也许这使得适配器的逻辑更容易,因为它只需处理“真实”列表项。
如果搜索视图应始终位于列表的顶部,并且不应使用它滚动,则只需将其移动到布局文件中的ListView上方即可。这可能是更好的用户体验。