在我的应用程序中,我有一个用户已安装应用程序的列表,并且希望为该列表创建一个搜索功能。现在,这里是我的编码:如何为搜索功能制定自定义过滤器
// create new adapter
AppInfoAdapter adapter = new AppInfoAdapter(this, Utilities.getInstalledApplication(this), getPackageManager());
// load list application
mListAppInfo = (ListView)findViewById(R.id.lvApps);
// set adapter to list view
mListAppInfo.setAdapter(adapter);
// search bar
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
// Drag_and_Drop_App.this.adapter.getFilter().filter(cs);
Drag_and_Drop_App.this.adapter.getFilter().filter(cs);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
,当我在这条线得到一个错误出现该问题:
Drag_and_Drop_App.this.adapter.getFilter().filter(cs);
它说,“用getFilter()”不是我的底座适配器定义,这是这样的:
package com.example.awesomefilebuilderwidget;
IMPORTS
public class AppInfoAdapter extends BaseAdapter {
private Context mContext;
private List mListAppInfo;
private PackageManager mPackManager;
public AppInfoAdapter(Context c, List list, PackageManager pm) {
mContext = c;
mListAppInfo = list;
mPackManager = pm;
}
@Override
public int getCount() {
return mListAppInfo.size();
}
@Override
public Object getItem(int position) {
return mListAppInfo.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// get the selected entry
ApplicationInfo entry = (ApplicationInfo) mListAppInfo.get(position);
// reference to convertView
View v = convertView;
// inflate new layout if null
if(v == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
v = inflater.inflate(R.layout.layout_appinfo, null);
}
// load controls from layout resources
ImageView ivAppIcon = (ImageView)v.findViewById(R.id.ivIcon);
TextView tvAppName = (TextView)v.findViewById(R.id.tvName);
TextView tvPkgName = (TextView)v.findViewById(R.id.tvPack);
// set data to display
ivAppIcon.setImageDrawable(entry.loadIcon(mPackManager));
tvAppName.setText(entry.loadLabel(mPackManager));
tvPkgName.setText(entry.packageName);
// return view
return v;
}
@Override
public Filter getFilter() {
// TODO Auto-generated method stub
return filter;
}
}
我添加了最后一部分“公共过滤器...”从四处张望在stackoverflow上。但现在,我需要一个自定义筛选器进行搜索。我可以使用什么? (我已经尝试的一件事,但它不工作)
如果您显示的是项目列表,那么扩展'ArrayAdapter'而不是'BaseAdapter'可能会有意义。 'ArrayAdapter'已经实现了'Filterable'接口,所以通过迁移你可以免费获得一个基本的过滤器。另外,特别是如果你需要更多的控制实际的过滤逻辑,你可以实现你自己的'过滤器'。关于如何做到这一点,有不少例子 - [这是一个](http://stackoverflow.com/a/14369336/1029225)。 –