我試圖根據用戶輸入的關鍵字來過濾listview的搜索欄,代碼沒有錯誤,但它根本沒有過濾。任何想法可能是什麼問題?我嘗試了各種方法,但沒有成功。從ArrayAdapter上的ListView過濾項目的問題
的OnCreate
super.onCreate(savedInstanceState);
// set layout for the main screen
setContentView(R.layout.layout_main);
// load list application
mListAppInfo = (ListView)findViewById(R.id.lvApps);
EditText search = (EditText)findViewById(R.id.EditText01);
mListAppInfo.setTextFilterEnabled(true);
// create new adapter
final AppInfoAdapter adapter = new AppInfoAdapter(this, Utilities.getInstalledApplication(this), getPackageManager());
// set adapter to list view
mListAppInfo.setAdapter(adapter);
search.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
Log.e("TAG", "ontextchanged");
adapter.getFilter().filter(s); //Filter from my adapter
adapter.notifyDataSetChanged(); //Update my view
}
});
一個ArrayAdapter類
public class AppInfoAdapter extends ArrayAdapter<ApplicationInfo> {
private Context mContext;
PackageManager mPackManager;
public AppInfoAdapter(Context c, List<ApplicationInfo> list, PackageManager pm) {
super(c, 0, list);
mContext = c;
mPackManager = pm;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// get the selected entry
ApplicationInfo entry = (ApplicationInfo) getItem(position);
Log.e("TAG", entry.toString());
// 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;
}
}
所以我應該在AppInfoAdapter中創建自己的過濾算法並重寫getFilter()方法? – dythe 2012-07-26 11:48:53
關閉但不完全。如果你想完全控制過濾算法,你的'AppInfoAdapter'應該擴展一個'BaseAdapter'並實現'Filterable'接口(大量可用的樣本) ,但是你可能想嘗試擴展'ApplicationInfo'類和重寫它的'toString()' – eladr 2012-07-26 12:03:43
那大概是什麼樣子? – dythe 2012-07-26 12:26:22