创建领域的通用搜索。我有RecyclerView
可以包含不同字符串值作为来自不同类的字段。
我使用SearchView
和SearchManager
实现了搜索功能
我面临的问题是代码的重复。 Recyclerview
具有来自不同类的字符串值,即CallReasonInfo,ObsercationInfo等。
现在我不得不创建不同的搜索查询来搜索所有这些类中的记录。
我正在寻找一种方法,我不需要为每种特定类型的RealmResults创建/添加监听器
lookupSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
RealmResults<CallReasonInfo> searchCallReasonInfo =
getCallReasonInfoQuery()
.contains("callReasonName",query)
.findAll();
searchCallReasonInfo.addChangeListener(new RealmChangeListener<RealmResults<CallReasonInfo>>() {
@Override
public void onChange(RealmResults<CallReasonInfo> elements) {
adapter.setSearchListAdapter(elements);
}
});
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
Log.e(TAG , "onQueryTextChange "+newText);
RealmResults<CallReasonInfo> searchCallReasonInfo =
getCallReasonInfoQuery()
.contains("callReasonName",newText.trim(), Case.INSENSITIVE)
.findAllAsync();
searchCallReasonInfo.addChangeListener(new RealmChangeListener<RealmResults<CallReasonInfo>>() {
@Override
public void onChange(RealmResults<CallReasonInfo> elements) {
adapter.setSearchListAdapter(elements);
}
});
return true;
}
});
适配器中的我有以下功能
public void setSearchListAdapter(RealmResults<E> results){
lookupInfo = results;
notifyDataSetChanged();
}
基于下面写的ListAdapter代码,我必须使用查询而不是可过滤的
public class SearchListAdapter <E extends RealmModel> extends RecyclerView.Adapter<SearchListAdapter.SearchListViewHolder>
implements View.OnClickListener {
private static final String TAG = "SearchListAdapter";
private RealmResults<E> lookupInfo;
private static String lookupType;
private static ItemClickListener itemClickListener;
public SearchListAdapter( RealmResults<E> resultInfo, String lookupType, ItemClickListener listener) {
this.lookupType = lookupType;
lookupInfo = resultInfo;
itemClickListener = listener;
}
@Override
public SearchListViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.seach_list_item, parent, false);
SearchListAdapter.SearchListViewHolder viewHolder = new SearchListAdapter.SearchListViewHolder(v);
return viewHolder;
}
@Override
public void onBindViewHolder(SearchListViewHolder holder, int position) {
holder.bind(lookupInfo.get(position));
}
@Override
public int getItemCount() {
return lookupInfo==null ? 0 : lookupInfo.size();
}
@Override
public void onClick(View v) {
Log.e(TAG , "Clicked "+v.getTag());
}
public static class SearchListViewHolder extends RecyclerView.ViewHolder {
private TextView tvItemName;
public SearchListViewHolder(View itemView) {
super(itemView);
tvItemName = (TextView) itemView.findViewById(R.id.tvItemName);
}
public void bind(final RealmModel item){
}
}
public void setSearchListAdapter(RealmResults<E> results){
lookupInfo = results;
notifyDataSetChanged();
}
}