我正在处理一个小的“搜索”实现。如果项目与查询匹配,则 listView 会显示这些项目。这很好用,但是每当隐藏并重新显示菜单并进行新查询时,所有“可搜索”都会继续堆积。如果我有 4 个应该显示,首先它会显示 4,然后是 8,然后是 12,等等。
private class Adapter extends BaseAdapter {
private LayoutInflater inflater;
public Adapter(){
inflater = LayoutInflater.from(getContext());
}
@Override
public int getCount() {
return menuItems.size();
}
@Override
public Object getItem(int position) {
return menuItems.get(position).text;
}
@Override
public long getItemId(int position) {
return menuItems.get(position).id;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder = new ViewHolder();
if (!isSearching) {
convertView = inflater.inflate(R.layout.rbm_item, null);
} else {
convertView = inflater.inflate(R.layout.rbm_search_item, null);
}
holder.subMenuList = (LinearLayout) convertView.findViewById(R.id.sub_holder);
holder.text = (TextView) convertView.findViewById(R.id.rbm_item_text);
convertView.setTag(holder);
convertView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (holder.subMenuList.getVisibility() == View.VISIBLE) {
holder.subMenuList.setVisibility(View.GONE);
} else {
holder.subMenuList.setVisibility(View.VISIBLE);
}
}
});
if (isSearching) {
holder.image = (ImageView) convertView.findViewById(R.id.rbm_item_icon);
holder.image.setImageResource(menuItems.get(position).icon);
holder.chapterId = (TextView) convertView.findViewById(R.id.id_text);
holder.chapterId.setText("Ch"+Integer.toString(menuItems.get(position).id));
} else {
holder.chapterId = (TextView) convertView.findViewById(R.id.rbm_item_id);
holder.chapterId.setText(Integer.toString(menuItems.get(position).id));
}
holder.text.setText(menuItems.get(position).text);
if (!isSearching) {
for (int i=0;i<menuItems.get(position).subItems.size();i++) {
TextView tv = new TextView(ctx);
tv.setTextColor(0xFF893658);
tv.setText(menuItems.get(position).subItems.get(i).getTitle());
tv.setCompoundDrawablesWithIntrinsicBounds(menuItems.get(position).subItems.get(i).getIcon(), 0, 0, 0);
tv.setCompoundDrawablePadding(5);
if (i == 0) {
if (menuItems.get(position).subItems.size() == 1) {
tv.setPadding(20, 20, 0, 20);
} else{
tv.setPadding(20, 20, 0, 10);
}
} else if (i == menuItems.get(position).subItems.size()-1){
tv.setPadding(20, 10, 0, 20);
} else {
tv.setPadding(20, 10, 0, 10);
}
holder.subMenuList.addView(tv);
}
}
return convertView;
}
class ViewHolder {
TextView text;
ImageView image;
LinearLayout subMenuList;
TextView chapterId;
}
}