我需要幫助爲當前正在處理的筆記應用程序中的列表視圖項目實現可篩選界面。我嘗試了幾種方法,但沒有得到預期的結果。現在它只是在綁定搜索項後不做任何事情。 我已經在我的適配器類和主要活動中實現了所有必要的方法。 我真的需要一些幫助,因爲我對此很陌生。感謝您期待積極的回覆。在陣列適配器上實現可篩選
// Note.java
public class Note implements Serializable {
private long mDateTime; //creation time of the note
private String mTitle; //title of the note
private String mContent; //content of the note
public Note(long dateInMillis, String title, String content) {
mDateTime = dateInMillis;
mTitle = title;
mContent = content;
}
public void setDateTime(long dateTime) {
mDateTime = dateTime;
}
public void setTitle(String title) {
mTitle = title;
}
public void setContent(String content) {
mContent = content;
}
public long getDateTime() {
return mDateTime;
}
}
public String getTitle() {
return mTitle;
}
public String getContent() {
return mContent;
}
}
// ArrayAdapter which implements Filterable
class NoteListAdapter extends ArrayAdapter<Note> implements Filterable{
List<Note> objects;
private List<Note> mStringFilterList;
Filter filter;
private static final int WRAP_CONTENT_LENGTH = 5;
public NoteListAdapter(Context context, int resource, List<Note> objects) {
super(context, resource, objects);
this.objects = objects;
this.mStringFilterList = objects;
}
@Override
public int getCount() {
return objects.size();
}
@Nullable
@Override
public Note getItem(int position) {
return objects.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public Filter getFilter() {
filter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence constraint) {
ArrayList<Note> tempList=new ArrayList<Note>();
FilterResults results = new FilterResults();
if (constraint != null && objects != null) {
for(Note singleNote : objects) {
if(singleNote.getTitle().contains(constraint))
tempList.add(singleNote);
}
results.values = tempList;
results.count = tempList.size();
}
return results;
}
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
objects = (ArrayList<Note>) results.values;
notifyDataSetChanged();
}
};
return filter;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = LayoutInflater.from(getContext())
.inflate(R.layout.list_component, parent, false);
}
return convertView;
}
}
// Main Activity
@Override
public boolean onQueryTextSubmit(String query) {
ArrayList<Note> notes = Utilities.getAllSavedNotes(getApplicationContext());
final NoteListAdapter na = new NoteListAdapter(this, R.layout.list_component, notes);
na.getFilter().filter(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
}
我已經實現你的解決方案你的解決方案,但獲得相同的結果。你可以請檢閱我的代碼嗎? – benboo
嘗試刪除'publishResults()'中的'if'語句並始終調用'notifyDataSetChanged()' –
我很感謝你的幫助,但它給出了相同的結果。 – benboo